JavaScript在多维JSON数组中循环
JavaScript looping through multimensional JSON arrays
我一直无法找到我的问题的正确解决方案。我想循环遍历嵌套的Products数组以显示每个Product名称。我写的东西有可能吗,或者我需要重新写一遍,让我更容易查询我需要的东西吗?
[
{
"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."
}
]
}
]
假设整个结构位于一个名为data
的变量中:
data.forEach(function(category) {
if (category.hasOwnProperty('product')) {
category.products.forEach(function(product) {
console.log(product.name);
});
}
});
外层forEach
循环遍历所有类别对象。内部forEach循环遍历每个类别中的所有产品对象。
一般来说,循环遍历数组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.
当然可以。
-
循环遍历数组[]:
for (initialization; condition; update) { ... }
-
遍历对象{}:
for (variable in object) { if (object.hasOwnProperty(variable)) { ... } }
相关文章:
- javascript:数组循环
- 如何将数组循环到JSON代码中
- 而与数组循环
- JavaScript 数组/循环不起作用
- AJAX在数组循环中调用,只在上一次完成后调用next
- 数组循环以获取单个值
- JavaScript数组循环
- Javascript 2D数组循环停止
- 通过Javascript中的JSON数组循环
- 为什么以下 forEach 数组循环未返回未定义
- 如何在数组循环中过滤数据
- 如何在数组循环 222 中过滤数据
- 数组循环以确定范围平均值
- 对象的数组循环
- 对象键及其值的数组循环
- 虽然的缺点!未定义的数组循环
- 数组循环导致无限循环
- 数组循环 - 处理下拉列表中的空值
- 在 Node 中连接数组循环.js glob 结果
- JavaScript 图像数组循环