0
for( var i = 0; i <= 5; i++ ){
    $('#item').data('level1', { 'level21': {i:'hello'}, 'level22': {i:'world'} } );
}

The keys for level21 and level22 is the string "i" and not a number 0-5 from the var i. level21 should be six times "hello" and level22 six times "world".

How can I fix that?

Thanks & regards,

Alex

1 Answer 1

3

You have to build your .data value the hard way, you'll also need to build the data in the loop and set it afterwards:

data = { level21: { }, level22: { } };
for( var i = 0; i <= 5; i++ ){
    data.level21[i] = 'hello';
    data.level22[i] = 'world';
}
$('#item').data('level1', data);

You have to use the [] form of object access to get i evaluated. You also need to build the data first to avoid overwriting the 'level1' every time through the loop.

Also, if you're only using contiguous integers starting at zero inside data.level21 and data.level22, then simple arrays might be a better choice than objects:

// Note the "{}" -> "[]" change in here
data = { level21: [ ], level22: [ ] };
// The syntax is the same for the rest
Sign up to request clarification or add additional context in comments.

1 Comment

@Alex: If you're only using numbers inside data.level21 and data.level22, then arrays (data = { level21: [ ], level22: [ ] };) might be a better choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.