gpt4 book ai didi

javascript - 嵌套对象结构

转载 作者:行者123 更新时间:2023-11-30 16:04:04 26 4
gpt4 key购买 nike

在下面的 fiddle 中:

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(s) - 开发、部署、支持 - 打印:

App1
ABC
Deploy
DEF
Deploy
GHI
Dev
Deploy
Support

有没有人看到我做错了什么?我的一部分认为这是对象结构,但我尝试了不同的变体,但没有任何效果。我必须忽略一些东西。

编辑:使用适当的对象结构更新了 Fiddle:https://jsfiddle.net/dzddv6pa/2/

最佳答案

在 javascript 对象中不能有重复的属性。如果你想拥有多个,你应该让 docTypes 成为一个数组。

{
"subAppName": "GHI",
"docs": [{
"docTypes": [{
"docTypeName": "Dev"
}, {
"docTypeName": "Deploy"
}, {
"docTypeName": "Support"
}]
}]
}

关于javascript - 嵌套对象结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37288085/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com