12

say I have an array like this:

const myArray = ['HP', 'QP', 'PS'];

And I'd like to have an object whose keys are myArray's values like

{ HP: 0, QP: 0, PS: 0 }

Is there a way to do the following in one line:

const myObj = {};
myArray.forEach(item => myObj[item] = 0);

4 Answers 4

16

Try using reduce:

const myArray = ['HP', 'QP', 'PS'];
const myObj = myArray.reduce((a, key) => Object.assign(a, { [key]: 0 }), {});
console.log(myObj);

In newer environments, you can also use Object.fromEntries:

const myArray = ['HP', 'QP', 'PS'];
const myObj = Object.fromEntries(myArray.map(key => [key, 0]));
console.log(myObj);

0
6

You could spread (spread syntax ...) mapped objects into one object with Object.assign.

var keys = ['HP', 'QP', 'PS'],
    object = Object.assign(...keys.map(key => ({ [key]: 0 })));
    
console.log(object);

2

A one liner:

console.log(
  ['HP', 'QP', 'PS']
    .map( v => ({[v]: 0}) )
    .reduce( (p, n) => ({...p, ...n}), {} )
);

2
console.log(['HP', 'QP', 'PS'] .reduce( (p, n) => ({...p, [n] :0 }), {} ));

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.