justanotherhobbyist
justanotherhobbyist

Reputation: 2192

Storing and retrieving objects in javascript array();

Hi I've searched for the answer but since the tutorials online are all friends = ("bob","fred","joe"); I dont get anywhere. I would like to be able to store several objects with 1-3 values in each index of the array like:

map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]

The object I have right now looks like:

node = {};
node = {ground:0, object:1};

But when I try the array way I can't access it, all I get "object Object". What would be the correct way to get the values from the map array one by one?

Upvotes: 0

Views: 161

Answers (2)

RobG
RobG

Reputation: 147363

Not sure what you want, or what you mean by "the array way", but if you want to get all the values for say ground, then:

var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}]

for (var i=0, iLen=map.length; i<iLen; i++) {
  alert(map[i].ground);
}

Edit

...
  alert('item ' + i + ' : ' + map[i].ground); // item 0 : 0
...

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Do you mean:


var map = [{ground:0},{ground:0, wall:1},{ground:0, item:3}];
for(var i = 0; i < map.length; i++) {
    console.log(map[i].ground + " item " + map[i].item);
}

Upvotes: 2

Related Questions