2

I'm trying to find out how to initialise an array of objects, where each object has the index (i) as its key and 0 as its value. The code below is not working as expected but I can't see why. I'm still quite beginner with Javascript and couldn't find an answer elsewhere.

var n = 10;
var sample = [];
for (var i = 0; i < n; i++)
    sample.push({i : 0});
3

4 Answers 4

3

you should use this syntax sample.push({[i]: 0});

when you need to access object property which is stored under some variable you should always use square brackets no matter you need write to or read from an object

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

Comments

3

The code below should take care of the job:

let n = 10;
let sample = Array.from({length:n}, (_, i) => ({ [i]: 0 }));

As pointed by Oleksandr Sakun on his answer, the index is used between brackets in order to evaluate the variable and set as a property of the object.

Comments

0

For a funcitonal approach you can try:

const initArray = (n)=>{
  const newArr = new Array(n).fill(0);
  return newArr.map((value, index)=> ({[index]: value}))
 }

Comments

-1

add square brackets to the index [i] :

  var n = 10;
  var sample = [];
  for (var i = 0; i < n; i++)
      sample.push({[i]: 0});
  console.log(sample);

4 Comments

This answer does not address the OP question.
it initializes and Array with n objects and i as key value. object value is 0. cant see why it shouldnt work for OP.
expected result is [{"0":0},{"1":0},{"2":0},{"3":0},{"4":0},{"5":0},{"6":0},{"7":0},{"8":0},{"9":0}] and this is not the result returned by your answer.
if this is the case, I have to edit it to sample.push({[i]: 0});

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.