admin管理员组

文章数量:1399474

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

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

Share Improve this question asked Apr 12, 2022 at 21:17 porFavorporFavor 4131 gold badge8 silver badges18 bronze badges 1
  • Please accept an answer as the solution to close the question – Majed Badawi Commented Apr 15, 2022 at 18:36
Add a ment  | 

3 Answers 3

Reset to default 6

Using Array#reduce:

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

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

console.log(res);

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

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

Using Object.assign and spread the array (with map).

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

const res = Object.assign({}, ...arr.map(key => ({[key]: true})));

console.log(res);

本文标签: