5

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
5
  • 2
    UGH*** Code formatting please! Commented Oct 30, 2009 at 14:26
  • 3
    Your first example myList[1].children[0].childname does work. Commented Oct 30, 2009 at 14:26
  • You mean carname... right crecentfresh... Put that in an answer and I will vote for it Commented Oct 30, 2009 at 14:27
  • @Zoidberg: not sure, question is looking for "Child21" I think. Commented Oct 30, 2009 at 14:32
  • Your first option is correct; if it's not working on your set-up, the problem is not with your code (as written). "Children" is a bad choice, probably, for its's ubiquity of use; are you using any libraries that are interfering due to naming conventions? Commented May 14, 2014 at 22:33

4 Answers 4

9

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>
Sign up to request clarification or add additional context in comments.

1 Comment

+1 to you and not the others because of the HTML example + 5 min earlier answer!
1

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

In FireFox's Firebug works

Comments

0

This does work...

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

Comments

0

Your first option...

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

should work just fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.