Problem looping through nested JavaScript objects and arrays
i need display the child value, but it display [object, object] like that so
Here my code:
var jsonObj = {"department":{
"Title1":[
{"child1":"Green",
"child2":"Yellow"
},
{"child3":"Black",
"child4":"White"
}
],
"Title2":[
{"child5":"Violet",
"child6":"purple"
},
{"child7":"Pink",
"child8":"Orange"
}
]
}
}
$(document).ready(function() {
var treeList = "";
treeList = "<ul id=\"createTree\">"; 开发者_JS百科
for(var key in jsonObj){
for(var subKey in jsonObj[key]){
alert(subKey);
//for(i=0; i<jsonObj[key].length;i++ ) {
treeList += ("<li>" + subKey + "<ul><li>"+jsonObj[key][subKey]+"</li></ul></li>");
//var b = $(c).text();
alert(treeList);
}
}
treeList += "</ul>";
$('#tree').append(treeList);
});
As Quentin said you need to keep drilling down, first into the array then into the objects contained within the array. The code below should access all the variables held in the JSON, you might have to restructure the HTML it outputs to get it looking as you want -
$(document).ready(function() {
var treeList = "";
treeList = "<ul id=\"createTree\">";
for(var key in jsonObj){
for(var subKey in jsonObj[key]){
alert(subKey);
for(i=0; i<jsonObj[key][subKey].length;i++ ) {
for(var arrayKey in jsonObj[key][subKey][i]){
treeList += ("<li>" + subKey + " - " + arrayKey + " - "+jsonObj[key][subKey][i][arrayKey]+"</li></ul></li>");
}
//var b = $(c).text();
alert(treeList);
}
}
}
treeList += "</ul>";
$('#tree').append(treeList);
});
The first jsonObj[key][subKey]
will be jsonObj.department.Title1
. This is an array.
When you stringify an array, it will, by default, produce the generic "This is an object" text.
If you want to display the data in it, you will have to keep going down to get at the strings.
精彩评论