我在JSON数组下面,我想使用像Item1,Item2,Item3等JavaScript动态获取数组名称。
如何在JavaScript中动态获取这些值
{
"products": {
"Item1": {
"name": "iPhone",
"price": 450
},
"Item2": {
"name": "iPad",
"price": 450
},
"Item3": {},
"Item4": {
"name": "iPod",
"price": 450
},
"Item5": {
"name": "MacBook"
}
}
}
答案 0 :(得分:1)
答案 1 :(得分:1)
取Object.keys()
获取密钥。
Object.keys()
方法返回给定对象自己的可枚举属性的数组,其顺序与for...in
循环提供的顺序相同(不同之处在于for-in循环枚举原型链中的属性。)
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>');
&#13;