2

Let us simplify my issue; I have this piece of code:

let arr = []
for (let i = 0; i < 2; i++) {
  arr.push({
    i: i + 1
  })
}
console.log(arr)

This outputs: Array [Object { i: 1 }, Object { i: 2 }]
But I want : Array [Object { 0: 1 }, Object { 1: 2 }] // Values of 'i' as object keys

How to achieve this?

Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130

2 Answers2

2

If you can use ES6 then this should work.

let arr = []
for(let i=0; i<2; i++) {
  arr.push({
    [i]: i+1
  })
}
console.log(arr)
Mark Baijens
  • 13,028
  • 11
  • 47
  • 73
deowk
  • 4,280
  • 1
  • 25
  • 34
2

You could use Array.from and take a single loop with an object with a computed property name.

var array = Array.from({ length: 2 }, (_, i) => ({ [i]: i + 1 }));

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392