Home > Software design >  How can I spread array elements into an object as the keys, and define some value for them?
How can I spread array elements into an object as the keys, and define some value for them?

Time:04-13

Let say I have an array:

const arr = ['a',  'b, 'c'];

I want to create an object like this:

{ 'a': true, 'b': true, 'c': true}

How can I do this?

const obj = {...arr: true} 

did not work

CodePudding user response:

Yeah, that's not a valid assignment. The first way that comes to mind - if you want one of those cool ES6 one-liners - would be:

const obj = Object.fromEntries(arr.map((el) => [el, true]));

CodePudding user response:

Using Array#reduce:

const arr = ['a', 'b', 'c'];

const res = arr.reduce((acc, key) => ({ ...acc, [key]: true }), {});

console.log(res);

  • Related