简体   繁体   中英

Javascript Multi-level array of JSON objects - how to access key-value pair in second level or higher

Consider the following array of JSON objects:

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"}]
    }
];

How does one access the "Child21" in javascript? The following options didn't work:

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

This worked OK for me:

myList[1].children[0].childname

This is also OK:

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

In full,

<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>

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

In FireFox's Firebug works

确实有效......

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

Your first option...

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

should work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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