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});
Felipe Plets
  • 7,230
  • 3
  • 36
  • 60
DSteman
  • 1,388
  • 2
  • 12
  • 25
  • 7
    {}Use computed property `{[i]: 0}` – ptothep Jan 18 '21 at 21:59
  • For the computed property documentation see: [MDN Object initializer - Computed property names](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names) – 3limin4t0r Jan 18 '21 at 22:23
  • Does this answer your question? [Convert object array to hash map, indexed by an attribute value of the Object](https://stackoverflow.com/questions/26264956/convert-object-array-to-hash-map-indexed-by-an-attribute-value-of-the-object) – Nuwan Alawatta Jan 18 '21 at 22:24

4 Answers4

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.

Felipe Plets
  • 7,230
  • 3
  • 36
  • 60
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

Oleksandr Sakun
  • 452
  • 4
  • 9
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}))
 }
Tomas Gonzalez
  • 188
  • 2
  • 8
-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);
alexrogo
  • 522
  • 3
  • 17