How can I iterate over an array of json object in Reactjs?
This is my json object which I am receiving from a websocket. Sometimes, I receive a single object in data variable & sometimes I receive multiple objects.
{"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}]}
Assume that you have that JSON object inside a variable called "temp".
then calling these will output:
now if you want to iterate over that array, simply use map()
function or use loops for that matter:
for (var i=0; i < temp.length; i++) {
// do something with temp[i]
// something like temp[i].symbol is valid!
}
or
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!
});
there are a lot of ways of using .map
function which I would recommend using for-loop, which for most of the times it is very simple and more understandable...!
Use the .map function on array, you shall end up with something that looks like:
<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/52062.html上一篇: 在C ++类中的三维向量