0

Possible Duplicate:
How do I add a property to a Javascript Object using a variable as the name?
Dynamic property names for loop of object Javascript

In success of javascript function I receveing data and it look like this:

data.lvl1
data.lvl2
data.lvl3
...

let say I have only 3 elements in data and I would like to loop for each of them and rise alert for every level:

for(a = 1; a<= 3; a++)
{
   alert(data.lvl + a);
   //I would like to read lvl1, lvl2, lvl3
}

This approach is obviously wrong. Please explain how to reach lvl1, lvl2 in loop when lvl number is based on increasing a.

Community
  • 1
  • 1
dllhell
  • 1,987
  • 3
  • 34
  • 51
  • If you only have those properties, you better use a `for...in` loop though (if the order does not matter): https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in. See als [How do I enumerate the properties of a javascript object?](http://stackoverflow.com/q/85992/218196). – Felix Kling Oct 22 '12 at 10:24

1 Answers1

2

If you want to access a property name using a string, then use square bracket notation.

foo.bar === foo['bar']

Such:

alert(data['lvl' + a]);

But it would be better to restructure your data so that you had something like:

data = { lvl: [1,2,3] }

instead of

data = { lvl1: 1, lvl2: 2, lvl3: 3 }
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you kind sir, feeling a little ashamed :) – dllhell Oct 22 '12 at 10:23
  • so should Quentin, for not bothering to find one of the dozens of other identical questions ;-) – Alnitak Oct 22 '12 at 10:23
  • yeah, it must be redundant question but I didn't know how to express my question in short way so I didn't find any helpfull answers. Sorry for that – dllhell Oct 22 '12 at 10:26