我一直无法找到解决问题的正确方法。我想遍历嵌套的Products数组以显示每个产品名称。是否可以用我所写的内容,或者我是否需要以允许我更容易查询我需要的方式重新编写它?
[
{
"category":"A",
"products":[
{
"id":1,
"name":"Product 1",
"description":"Description of my product 1."
},
{
"id":2,
"name":"Product 2",
"description":"Description of my product 2."
},
{
"id":3,
"name":"Product 3",
"description":"Description of my product 3."
}
]
},
{
"category":"B",
"products":[
{
"id":4,
"name":"Product 4",
"description":"Description of my product 4 in cat B."
},
{
"id":5,
"name":"Product 5",
"description":"Description of my product 5 in cat B."
},
{
"id":6,
"name":"Product 6",
"description":"Description of my product 6 in cat B."
}
]
}
]
答案 0 :(得分:1)
假设整个结构位于名为data
的变量中:
data.forEach(function(category) {
if (category.hasOwnProperty('product')) {
category.products.forEach(function(product) {
console.log(product.name);
});
}
});
外部forEach
循环遍历所有类别对象。内部forEach循环遍历每个类别中的所有产品对象。
答案 1 :(得分:1)
通常,循环遍历数组things = [...]
的方法如下:
for( var i=0; i<thing.length; i++ ) {
// do stuff with thing[i]
}
循环遍历对象things = {...}
就像这样:
for( key in things ) {
if( things.hasOwnProperty(key) ) {
// do stuff with things[key] or key.
}
}
你可以随心所欲地嵌套它们。
在您的情况下,如果我们将原始数据结构命名为items
,那么
(见http://jsfiddle.net/7yc5arLe/):
for( item=0; item<items.length; item++ ) {
console.log('category is '+items[item].category);
for( product=0; product<items[item].products.length; product++ ) {
p = items[item].products[product];
for( key in p ) {
console.log(' product '+key+' is '+items[item].products[product][key]);
}
}
}
将输出
category is A
product id is 1
product name is Product 1
product description is Description of my product 1.
product id is 2
product name is Product 2
product description is Description of my product 2.
product id is 3
product name is Product 3
product description is Description of my product 3.
category is B
product id is 4
product name is Product 4
product description is Description of my product 4 in cat B.
product id is 5
product name is Product 5
product description is Description of my product 5 in cat B.
product id is 6
product name is Product 6
product description is Description of my product 6 in cat B.
答案 2 :(得分:0)
当然有可能。
循环遍历数组[]:
for (initialization; condition; update) {
...
}
循环对象{}:
for (variable in object) {
if (object.hasOwnProperty(variable)) {
...
}
}