简体   繁体   中英

how to fetch JSON array name dynamically in Javascript

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"
        }
    }
}

Use a for..in loop,

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

Working example

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>'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM