Pravissimo Pravissimo - 1 month ago 10
Javascript Question

How to access element in returned object using javascript?

I've been given a socket which returns me an object.

And i'd like to access one of its values, however I don't know how to.
What i need is a "balance" value for every object.

Down below there is a screenshot from my console.
Thanks for the help in advance

enter image description here

Answer

On both cases you need to access the properties by [] notation.

1) You can do it in for in loop

var obj = /**/; //Your object

for(key in obj.message){
  
  if(obj.message.hasOwnProperty(key)){
          obj.message[key].balance <- use this syntax to get the balance of each item
    }
}

2) Or via Object.keys()

var obj = {
  message:{
    item1:{
       balance: 1000
    },
    item2:{
      balance: 2000
    }
  }  
};

Object.keys(obj.message).forEach(key => console.log(obj.message[key].balance));