0

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}]}
Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21
aditya singh
  • 51
  • 1
  • 3

2 Answers2

2

Assume that you have that JSON object inside a variable called "temp".

then calling these will output:

  • temp.table // output: "orderBookL2"
  • temp.action // output: "update"
  • temp.data // output: [...] an array

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...!

Moher
  • 741
  • 7
  • 17
0

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

Laurens Mäkel
  • 815
  • 2
  • 12
  • 29