2

I have an object like this:

var obj{}; 

I want to set object values dynamically like so:

for(i=0;i<10;i++) { quest='quest'+i; header='header'+i; $(obj).data(quest,{header:i}); quest,header=0; } 

I'm expecting object to be saved like:

obj{quest1:{header1:1}, quest2:{header2:2} quest3:{header3:3} 

But they are saved like:

obj{quest1:{header:1}, quest2:{header:2}, quest3:{header:3}, 

The header-key in my object is not getting the actual value. but simply save as "header"..

Could you please guide me here?

3 Answers 3

2

You can write:

var obj = {}; for(i=1; i<11; i++) { quest='quest'+i; header='header'+i; obj[quest] = {}; obj[quest][header] = i; } 
Sign up to request clarification or add additional context in comments.

Comments

1

In your code your loop starts with i = 0 but the properties start by 1.

var quest, header, obj = {}; for (i = 0; i < 10; i += 1) { quest = 'quest' + (i + 1); header = 'header' + (i + 1); obj[quest] = {}; obj[quest][header] = (i + 1); } 

Comments

0

You cannot have a variable key in an object literal.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.