0

How can I retrieve an object child using other variable.

The Code

var product = {
  '123':{
    'name':'Basket',
    'price':'12.30'
  }
}

var id = 123;

var basket_price = product.id.price;    // I want to use the id value
                                        // as the reference to
                                        // retrieve the object child

How is the correct way to achieve that? Apparently the above way is unsuccessful because I don't specify any child with the key name of 'id' in the object definition.

  • 1
    `var basket_price = product[id].price;`. – Striped Mar 10 '18 at 12:01
  • 2
    Possible duplicate of [How do I access properties of a javascript object if I don't know the names?](https://stackoverflow.com/questions/675231/how-do-i-access-properties-of-a-javascript-object-if-i-dont-know-the-names) – Striped Mar 10 '18 at 12:02

1 Answers1

0
var product = {
  '123':{
    'name':'Basket',
    'price':'12.30'
  }
}

var id = 123;

var basket_name = product[id].name; 
alert(basket_name);
var basket_price = product[id].name; 
alert(basket_price);
hiren
  • 1,067
  • 1
  • 9
  • 16