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);
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With