Question

I have looked everywhere for this but nobody seems to use associative arrays in objects. Here is my object:

var player = {
     Level: 1,
     Stats: [{Defense : 5}, {Attack: 1}, {Luck: 3}]
};

I need to access the values of Defense, Attack, and Luck, but how?

I have tried this but it hasn't worked:

player.Stats.Defense
player.Stats.Attack
player.Stats.Luck

Any ideas? Thanks!

P.S. Does it make a difference that I am using jQuery?

Was it helpful?

Solution

You've said you're in control of the structure. If so, change it to this:

var player = {
     Level: 1,
     Stats: {Defense : 5, Attack: 1, Luck: 3}
};

Note that Stats is now an object, not an array. Then you access that information the way you tried to, player.Stats.Defense and so on. There's no reason to make Stats an array of dissimilar objects, that just makes your life difficult.

You've used the term "associative array" which makes me think you have a PHP background. That term isn't commonly used in the JavaScript world, to avoid confusion with arrays. "Object," "map," or "dictionary" are the terms usually used, probably in that order, all referring to objects ({}). Probably nine times out of ten, if you would use an associative array for something in PHP, you'd use an object for it in JavaScript (in addition to using objects for the same sort of thing you use objects for in PHP).

P.S. Does it make a difference that I am using jQuery?

No, this is language-level rather than library-level, but it's a perfectly reasonable question.


(Making this a CW answer because it's basically what all the comments on the question are saying.)

OTHER TIPS

as Stats: [{Defense : 5}, {Attack: 1}, {Luck: 3}] is array of objects, you need to do:

player.Stats[0].Defense
player.Stats[1].Attack
player.Stats[2].Luck

Here player.Stats is an array of objects. So you'll have to use index for accessing those objects.

var player = {
     Level: 1,
     Stats: [{Defense : 5}, {Attack: 1}, {Luck: 3}]
};

Use these :

player.Stats[0].Defense
player.Stats[1].Attack
player.Stats[2].Luck
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top