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?
3 Answers 3
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']);
Comments
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
Always console.log(anything) for better understanding of the object.
The following change was needed.
var item = objA ['1'][0];
objAis 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[].