这是我从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}]}
答案 0 :(得分:2)
假设您在名为“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,这在大多数情况下都非常简单,更容易理解......!
答案 1 :(得分:0)
在数组上使用.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