JavaScript在多维JSON数组中循环
我在这里找不到解决问题的正确方法。我想循环使用嵌套的Products数组来显示每个产品名称。我写的东西是否可能,或者我是否需要以一种更容易查询我需要什么的方式重新编写它JavaScript在多维JSON数组中循环,javascript,arrays,json,multidimensional-array,Javascript,Arrays,Json,Multidimensional Array,我在这里找不到解决问题的正确方法。我想循环使用嵌套的Products数组来显示每个产品名称。我写的东西是否可能,或者我是否需要以一种更容易查询我需要什么的方式重新编写它 [ { "category":"A", "products":[ { "id":1,
[
{
"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."
}
]
}
]
当然有可能
- 要在数组[]上循环,请执行以下操作:
for (initialization; condition; update) { ... }
- 要在对象{}上循环,请执行以下操作:
for (variable in object) { if (object.hasOwnProperty(variable)) { ... } }
data
的变量中:
data.forEach(function(category) {
if (category.hasOwnProperty('product')) {
category.products.forEach(function(product) {
console.log(product.name);
});
}
});
外部
forEach
循环遍历所有类别对象。内部forEach循环遍历每个类别中的所有products对象。通常,通过数组things=[…]
的循环如下:
for( var i=0; i<thing.length; i++ ) {
// do stuff with thing[i]
}
for( key in things ) {
if( things.hasOwnProperty(key) ) {
// do stuff with things[key] or key.
}
}
你可以随心所欲地把它们安顿好
在您的情况下,如果我们将原始数据结构命名为项
,则
(见):
我想你要找的已经在这里得到了回答:
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.