Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 897
porFavor Avatar asked Oct 18 '25 13:10

porFavor


1 Answers

Using Array#reduce:

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

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

console.log(res);
like image 175
Majed Badawi Avatar answered Oct 20 '25 03:10

Majed Badawi