Javascript JSON对象的多级数组 - 如何在第二级或更高级别访问键值对

时间:2009-10-30 14:24:03

标签: javascript json multidimensional-array

考虑以下JSON对象数组:

myList = [
    {title:"Parent1",
        children:[{childname:"Child11"},
                     {childname:"Child12"}],
        cars:[{carname:"Car11"},
              {carname:"Car12"}]
    },
    {title:"Parent2",
        children:[{childname:"Child21"},
                     {childname:"Child22"}],
        cars:[{carname:"Car21"},
              {carname:"Car22"}]
    }
];

如何在javascript中访问“Child21”?以下选项不起作用:

var myString = myList[1].children[0].childname; //Does not work
var myString = myList[1]["children"][0].childname; //Does not work

4 个答案:

答案 0 :(得分:9)

这对我来说很合适:

myList[1].children[0].childname

这也没关系:

myList[1]["children"][0].childname;

完整,

<html>
<body>
<script>
var myList = [
    {title:"Parent1",
        children:[{childname:"Child11"},
                     {childname:"Child12"}],
        cars:[{carname:"Car11"},
              {carname:"Car12"}]
    },
    {title:"Parent2",
        children:[{childname:"Child21"},
                     {childname:"Child22"}],
        cars:[{carname:"Car21"},
              {carname:"Car22"}]
    }
];
alert (myList[1].children[0].childname);
</script>
</body>
</html>

答案 1 :(得分:1)

var myString = myList [1] .children [0] .childname;

在FireFox的Firebug作品中

答案 2 :(得分:0)

工作......

alert(myList[1].children[0].childname);

答案 3 :(得分:0)

你的第一个选择......

var myString = myList[1].children[0].childname;

应该可以正常工作。