我如何迭代Reactjs中的一个json对象数组?
这是我从websocket接收的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}]}
假设你在一个叫做“temp”的变量中有这个JSON对象。
然后调用这些将输出:
现在如果你想遍历数组,只需使用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!
});
有很多使用.map
函数的方法,我会推荐使用for-loop,这在大多数情况下都是非常简单和可以理解的。
在数组上使用.map函数,最终得到的结果如下所示:
<ul>
obj.arrayProperty.map( (singleObj, index) =>
<li key={index}>Symbol: {singleObj.symbol} Id: {singleObj.id} Side: {singleObj.side} Size: {singleObj.size}</li>
)
</ul>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
链接地址: http://www.djcxy.com/p/52061.html上一篇: How can I iterate over an array of json object in Reactjs?
下一篇: Looping in JSX files