Reputation: 1095
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?
Upvotes: -1
Views: 94
Reputation: 686
Always console.log(anything)
for better understanding of the object.
The following change was needed.
var item = objA ['1'][0];
Upvotes: 1
Reputation: 70552
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']);
Upvotes: 2
Reputation: 66663
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..
Upvotes: 2