[英]How to loop through this json array using javascript
我尝试循环此 json 但它不起作用。我想循环浏览商店但它不起作用
json:
{
"type": "shops",
"shops": {
"1": {
"id": "1",
"name": "abcd",
"open_time": "9AM",
"closed_time": "9PM"
},
"2": {
"id": "1",
"name": "efgh",
"open_time": "9AM",
"closed_time": "9PM"
}
}
}
剧本
$.getJSON( "simple.json", function( json ) {
console.log( "JSON Data: " + (json) );
for(var i = 0; i < json.shops.length; i++){
console.log(json[i].shops.name);
}
});
这不会给我任何结果
json.shops
不是数组,而是一个对象。 您可以使用for..in
循环或$.each
使用 $.each
$.getJSON( "simple.json", function( json ) {
console.log( "JSON Data: " + (json) );
$.each(json.shops, function(key, shop){
//key will be "1", "2"...n
console.log(shop.name, shop.id);
});
});
使用 for..in
for(var shop in json.shops){
//shop will be "1", "2"...n
if (json.shops.hasOwnProperty(shop))
console.log(json.shops[shop].name);
}
如评论所示,商店是一个对象,而不是一个数组。 您可以使用以下命令遍历 javascript 对象的所有属性:
$.getJSON( "simple.json", function( json ) {
console.log( "JSON Data: " + (json) );
for(var key in json.shops){
if (!json.shops.hasOwnProperty(key)) continue;
console.log(json.shops[key]);
}
});
json.shops.length
未定义,因为shops
是一个对象而不是数组,并且(在这种情况下)没有“长度”属性。 但是每个 JavaScript 对象都可以有属性,并且这些属性名称可以作为列表检索,然后您可以对其进行迭代:
for(var i = 0; i < Object.keys(json.shops).length; i++){
console.log(json.shops[Object.keys(json.shops)][i].name);
}
或者,也可以将对象的键作为数组获取,并使用数组内置的forEach
函数:
Object.keys(json.shops).forEach(function(element, arrayIndex, array) {
console.log(array[element].name);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.