简体   繁体   English

循环通过嵌套的 JavaScript 对象和 arrays 的问题

[英]Problem looping through nested JavaScript objects and arrays

i need display the child value, but it display [object, object] like that so我需要显示子值,但它会像这样显示 [object, object]

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\">";     
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);
});

The first jsonObj[key][subKey] will be jsonObj.department.Title1 .第一个jsonObj[key][subKey]将是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.如果要在其中显示数据,则必须继续向下以获取字符串。

As Quentin said you need to keep drilling down, first into the array then into the objects contained within the array.正如 Quentin 所说,您需要继续向下钻取,首先进入阵列,然后进入阵列中包含的对象。 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 -下面的代码应该访问 JSON 中保存的所有变量,您可能必须重组它输出的 HTML 以使其看起来像您想要的那样 -

$(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);
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM