在下面的小提琴中:
https://jsfiddle.net/dzddv6pa/
console.clear();
var data = {
"apps": [{
"appName": "App1",
"subApps": [{
"subAppName": "ABC",
"docs": [{
"docTypes": [{
"docTypeName": "Deploy"
}]
}]
}, {
"subAppName": "DEF",
"docs": [{
"docTypes": [{
"docTypeName": "Deploy"
}]
}]
}, {
"subAppName": "GHI",
"docs": [{
"docTypes": {
"docTypeName": "Dev"
},
"docTypes": {
"docTypeName": "Deploy"
},
"docTypes": {
"docTypeName": "Support"
}
}]
}]
}]
};
var apps = data.apps;
var appsLen = apps.length;
for (var i = 0; i < appsLen; i++) {
var app = apps[i];
var appName = app.appName;
console.log(appName);
var subApps = app.subApps;
var subAppsLen = subApps.length;
for (var j = 0; j < subAppsLen; j++) {
var subApp = subApps[j];
var subAppName = subApp.subAppName;
console.log("\t" + subAppName);
var docs = subApp.docs;
var docsLen = docs.length;
for (var k = 0; k < docsLen; k++) {
var doc = docs[k];
var docTypes = doc.docTypes;
var docTypesLen = docTypes.length;
for (var l = 0; l < docTypesLen; l++) {
var docType = docTypes[l];
var docTypeName = docType.docTypeName;
console.log("\t\t" + docTypeName);
}
}
}
}
我循环遍历data
变量,试图将以下结构打印到控制台,但我不能在我的生活中获得GHI下的docTypeName - Dev,部署,支持 - 打印:
App1
ABC
Deploy
DEF
Deploy
GHI
Dev
Deploy
Support
有谁看到我做错了什么?我的一部分认为它是对象结构,但我尝试了不同的变化,没有任何作用。我必须忽略一些东西。
编辑:使用适当的对象结构更新了小提琴:https://jsfiddle.net/dzddv6pa/2/
答案 0 :(得分:2)
您不能在javascript对象中拥有重复的属性。如果你想拥有多个数组,你应该让docTypes
成为一个数组。
{
"subAppName": "GHI",
"docs": [{
"docTypes": [{
"docTypeName": "Dev"
}, {
"docTypeName": "Deploy"
}, {
"docTypeName": "Support"
}]
}]
}