Reputation: 627
In the following 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);
}
}
}
}
I’m looping through the data
variable, trying to print the following structure to the console, but I can’t for the life of me get the docTypeName(s) under GHI - Dev, Deploy, Support - to print:
App1
ABC
Deploy
DEF
Deploy
GHI
Dev
Deploy
Support
Does anyone see what I’m doing wrong? Part of me thinks it’s the object structure, but I’ve tried different variations and nothing works. I have to be overlooking something.
EDIT: Updated Fiddle with proper Object struct: https://jsfiddle.net/dzddv6pa/2/
Upvotes: 1
Views: 69
Reputation: 4435
You can't have duplicate properties in a javascript object. You should make docTypes
be an array if you want to have multiple of them.
{
"subAppName": "GHI",
"docs": [{
"docTypes": [{
"docTypeName": "Dev"
}, {
"docTypeName": "Deploy"
}, {
"docTypeName": "Support"
}]
}]
}
Upvotes: 2