up vote 1 down vote favorite

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
link|flag
UGH*** Code formatting please! – Zoidberg Oct 30 '09 at 14:26
2  
Your first example myList[1].children[0].childname does work. – Crescent Fresh Oct 30 '09 at 14:26
You mean carname... right crecentfresh... Put that in an answer and I will vote for it – Zoidberg Oct 30 '09 at 14:27
@Zoidberg: not sure, question is looking for "Child21" I think. – Crescent Fresh Oct 30 '09 at 14:32

4 Answers

up vote 3 down vote

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>
link|flag
+1 to you and not the others because of the HTML example + 5 min earlier answer! – Seb Oct 30 '09 at 14:34
up vote 0 down vote

This does work...

alert(myList[1].children[0].childname);
link|flag
up vote 0 down vote

Your first option...

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

should work just fine.

link|flag
up vote 0 down vote

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

In FireFox's Firebug works

link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.