-1

I am trying to create a Array of Array containing objects,

Here is my code,

var objA = new Array();

function myFunction(){
     objA ['1'] = new Array();
     objA ['1'].push({'bird':'parrot','animal':'rabbit'});
     var item = objA ['1'];
     alert(item['bird']);
}

Now ideally above code should alert 'parrot', but instead I get 'undefined'.
What am I doing wrong?

2
  • 1
    objA is an array but you're passing a string "index", which will work but unexpectedly. Use an object instead, {}. Btw, you can declare an array simply as []. Commented Dec 13, 2012 at 6:21
  • Sounds like you'd rather want an array of objects instead of an array of arrays of objects. Commented Dec 13, 2012 at 6:56

3 Answers 3

2

You set the attribute to a new array:

objA ['1'] = new Array();

So, of course, when you retrieve it, you're getting back an array.

var item = objA ['1'];

Arrays don't have a bird attribute. The first item in the array does, though.

alert(item[0]['bird']);
Sign up to request clarification or add additional context in comments.

Comments

2

You should use:

var item = objA ['1'][0];

When you do objA ['1'].push(..) you are appending an item to the array objA ['1'] - whose items should be referenced by index like objA ['1'][0], objA ['1'][1] etc..

Comments

1

Always console.log(anything) for better understanding of the object. The following change was needed.

var item = objA ['1'][0];

http://jsfiddle.net/rpnzG/

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.