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?
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?
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)
You could take Object.fromEntries
.
const result = Object.fromEntries(Array.from({ length: 10 }, (_, i) => [i + 1, 0]));
console.log(result);
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)