1

So, Basically i was trying to create an object like

{
'1': 0, 
'2': 0, 
'3': 0,
.....
'9': 0
}

Is there any "javaScriptic" trick to do so?

Aedvald Tseh
  • 1,757
  • 16
  • 31
Arnob
  • 21
  • 4
  • Related (but not the same): [arrays - Does JavaScript have a method like "range()" to generate a range within the supplied bounds? - Stack Overflow](https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp) and [javascript - How to create an array containing 1...N - Stack Overflow](https://stackoverflow.com/questions/3746725/how-to-create-an-array-containing-1-n) – user202729 Feb 06 '21 at 09:21

3 Answers3

3

You can use new Array(10) to create an array of 10 items, fill it with 0, and then spread it to an object.

Note: using this method, the first key would be 0, and not 1.

const obj = { ...new Array(10).fill(0) }

console.log(obj)

To get an object that starts with 1, you can use destructuring with rest (...) to get an object with all properties, but 0:

const { 0: _, ...obj } = { ...new Array(10).fill(0) }

console.log(obj)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

You could take Object.fromEntries.

const result = Object.fromEntries(Array.from({ length: 10 }, (_, i) => [i + 1, 0]));

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

You could do one-liner like this

Because you want the key to be from 1, so init an array of size 9 and map the value by increased-by-one index. From that, reduce with the start of empty object to get your expected output

const res = Array
  .from({ length: 9 }, (_, index) => index + 1)
  .reduce((acc, el) => ({ ...acc, [el]: 0 }), {})

console.log(res)
hgb123
  • 13,869
  • 3
  • 20
  • 38