0

我一直致力于显示来自 JSON 提要的值 -非常感谢我在这里阅读的许多以前的帖子的帮助 - 我现在可以在主数组中写入(在浏览器中显示)我的对象的所有值但是对于“嵌套”在数组 > 对象 > 数组 > 对象 > 属性:值结构中的“名称”对象的值(如下所示)。想知道是否有人可以帮助我找到一种方法来成功地交互和展示这个级别 - 我觉得我现在已经没有什么想法了:-(

非常感谢一个想法。我一直在使用标准的 JavaScript 而不是我应该添加的 JQuery。

var foo=[ 
    {
        "subjects": 
        [
            "A1",
            "SB2"
        ],
        "title": "Box World",
        "first_pub": "2013-12",
        "characters": 
        [
            {
                "name": 
                {
                    "given": "Maxwell",
                    "honourific": "",
                    "family": "Smart"
                },
                "id": "MS34"
            }, 
            {
                "name": 
                {
                    "given": "Samantha",
                    "honourific": "",
                    "family": "Stevens"
                },
                "id": "SS81"
            } // end creators object 2
        ],
        "publisher": "Galactic Publishing"
    },
    {
        "subjects": 
        [
            "A133",
            "PB82"
        ],
        "title": "Octonautica",
        "first_pub": "2010",
        "characters": 
        [
            {
                "name": 
                {
                    "given": "Peso",
                    "honourific": "Doctor",
                    "family": ""
                },
                "id": "MS34"
            },
            {
                "name": 
                {
                    "given": "Barnacle",
                    "honourific": "Captain",
                    "family": ""
                },
                "id": "SS82"
                } 
            ],
        "publisher": "Neptune House"
    }   
]


var obj_set = foo ;

for (var key in obj_set) {
   document.write("\<h3\> Publication " + key + "\<\/h3\>" );
   var obj = obj_set[key];
   document.write("\<ol\>");

   for (var prop in obj) {
      document.write("\<li\>" + prop + " = " + obj[prop] + "\<\/li\>" );
   }
   document.write("\<\/ol\>");

}   
//END MAIN KEY LOOP
4

1 回答 1

1

试试这个:

var i, j;

// iterate over main array foo
for (i=0; i<foo.length; i++) {

    // iterate over characters array
    for(j=0; j<foo[i].characters.length; j++) {

        // each item contains an object "name"
        var name = foo[i].characters[j].name;

        console.log(name.honorific + ' ' + name.given + ' ' + name.family);
    }
}
于 2013-07-15T12:53:58.347 回答