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}]}
2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.