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?

1

3 Answers 3

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)

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

Comments

1

You could take Object.fromEntries.

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

console.log(result);

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.