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.

1

1 Answer 1

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 }
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you kind sir, feeling a little ashamed :)
so should Quentin, for not bothering to find one of the dozens of other identical questions ;-)
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.