Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set object keys from array value in one line

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);
like image 773
t3__rry Avatar asked Jun 23 '18 08:06

t3__rry


2 Answers

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);
like image 149
CertainPerformance Avatar answered Nov 05 '22 23:11

CertainPerformance


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);
like image 23
Nina Scholz Avatar answered Nov 06 '22 00:11

Nina Scholz