0

I've below JSON array, I want to fetch array name dynamically using JavaScript like Item1, Item2, Item3 etc.

How to get these values dynamically in JavaScript

{
    "products": {
        "Item1": {
            "name": "iPhone",
            "price": 450
        },
        "Item2": {
            "name": "iPad",
            "price": 450
        },
        "Item3": {},
        "Item4": {
            "name": "iPod",
            "price": 450
        },
        "Item5": {
            "name": "MacBook"
        }
    }
}
java begineer
  • 319
  • 5
  • 15

2 Answers2

1

Use a for..in loop,

for (var key in obj.products) {
    console.log(key);
}

Working example

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Hi, Its working but if I try to fetch name using key.name I'm getting undefined. How to get name and price value. In some case price is not there for example in Item5 and few cases both name and price not available. How to handle such cases? – java begineer Mar 31 '16 at 21:13
  • The issue there is because `key` is just the string name of the property. To get the `price` value from its object value, you need to use `obj.products[key].price`, along with some logic to check if that object actually exists; here's an example; https://jsfiddle.net/0nLpmakg/1/ – Rory McCrossan Mar 31 '16 at 21:24
1

Take Object.keys() for getting the keys.

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

var object = { "products": { "Item1": { "name": "iPhone", "price": 450 }, "Item2": { "name": "iPad", "price": 450 }, "Item3": {}, "Item4": { "name": "iPod", "price": 450 }, "Item5": { "name": "MacBook" } } };

document.write('<pre>' + JSON.stringify(Object.keys(object.products), 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392