0

The following code:

    for(i=0; i<3; i++){
         a = {};
         a['name' + i] = i;
        data.push(a);
}

...outputs the following array:

{
1:{name0:0},
2:{name1:1},
3:{name2:2}
}

How can I amend the code so that it outputs the array as follows:

{
name0:0,
name1:1,
name2:2
}

The reason I need to do this, is that I'd like to be able to reference my array later on like so: data[name1], instead of having to loop through the entire array to look for the value that I need.

2
  • 1
    Use a plain object instead of an array data = {} and then use data['name' + i] = i in the loop. You don't need a. Commented Mar 2, 2017 at 2:10
  • 1
    they don't need to push; Commented Mar 2, 2017 at 2:14

1 Answer 1

3

well you should use data directly as an object, rather than having it as an array (and thus having it as an array of objects)

 for(i=0; i<3; i++){
    data['name' + i] = i;
}

Keep in mind that data should be an object (initialized as var data = {})

Sign up to request clarification or add additional context in comments.

2 Comments

This is the correct answer. My mistake was trying to push the values into the array each time. I will accept this answer as correct.
Do you need to initialize data ... var data = {};? OP has not shown how data is initialized but from the operations it's var data = [];.

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.