2017-09-01 84 views
-4

这是我从websocket收到的json对象。 有时,我收到数据变量&中的单个对象,有时我收到多个对象。如何迭代Reactjs中的json对象数组?

{"table":"orderBookL2","action":"update","data": 
[{"symbol":"XBTU17","id":28499951430,"side":"Sell","size":97140}, 
{"symbol":"XBTU17","id":28499951510,"side":"Buy","size":48707}, 
{"symbol":"XBTU17","id":28499951517,"side":"Buy","size":97414}, 
{"symbol":"XBTU17","id":28499951910,"side":"Buy","size":243535}, 
{"symbol":"XBTU17","id":28499952128,"side":"Buy","size":487069}]} 
+1

[React JSX内部循环可能重复](https://stackoverflow.com/questions/22876978/loop-inside-react-jsx) –

+0

[ReactJs中渲染数组]可能的重复(https:// stackoverflow的.com /问题/ 45078848 /渲染一个阵列式-reactjs) –

回答

1

假设你有一个变量中JSON对象被称为“临时”。

然后调用这些将输出:

  • temp.table //输出: “orderBookL2”
  • temp.action //输出: “更新”
  • temp.data //输出:[ ...]数组

现在如果你想遍历数组,只需使用map()功能或使用循环为此事:

for (var i=0; i < temp.length; i++) { 
    // do something with temp[i] 
    // something like temp[i].symbol is valid! 
} 

temp.map(do_sth(item, index)); 
// here do_sth() is a function that gets an item of temp array and also 
// index of that item 
// or you can even define the function inside the map() function like this: 
temp.map(function(item, index){ 
    // do sth with item or temp[index] which former is recommended 
    // sth like item.symbol is valid! 
}); 

有很多的,我会建议使用for循环使用.map功能的方式,这对于大多数时候它是非常简单和更容易理解......!