[英]looping through JSON object to get to the content of an array
我为这段代码而烦恼:
{
"Carrefour": [
{ "geography": [ "Europe", "Germany" ], "productLine": "Produce", "revenue": { "2022": 130143, "2021": 172122, "2020": 103716 } },
{ "geography": [ "Europe", "France" ], "productLine": "Clothing", "revenue": { "2022": 85693, "2021": 91790, "2020": 77650 } },
],
"Tesco": [
{ "geography": [ "Europe", "United Kingdom" ], "productLine": "Electronics", "revenue": { "2022": 239537, "2021": 131959, "2020": 97047 } },
{ "geography": [ "Europe", "Ireland" ], "productLine": "Produce", "revenue": { "2022": 74963, "2021": 43406, "2020": 54623 } },
]
}
我试图遍历这段代码以获取所有内容。
但是,我不知道如何到达该地区(欧洲)。 我试过了
function (json) {
for (var company in json) {
region = json[company].geography[0];
}
}
但是它返回undefined,因为company是一个数组。 实际上json.Carrefour[0].geography[0];
正确返回“欧洲”。
如何将公司作为数组访问并保留名称? 我不能直接使用这个名字!
谢谢。
您的公司被分配了数组,因此您需要一个内部循环。
for (var company in json) {
for (var i = 0; i < json[company].length; i++) {
region = json[company][i].geography[0];
}
}
这是一个演示: http : //jsfiddle.net/dkPWt/
演示输出:
Carrefour:
Europe
Europe
Tesco:
Europe
Europe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.