-1

What's the best way to convert a string array into an object? Is there any one line ES6 code not foreach function?

Array:

["FirstName", "MiddleName", "LastName"]

Expected object:

{ LastName: true, MiddleName: true, FirstName: true }
WangHongjian
  • 383
  • 6
  • 16
  • 1
    There are lots of different ways. Which ones have you attempted? Which ones worked? Which ones didn't work? You should add the code you've attempted to your question as a [mcve]. – Andy May 19 '22 at 10:12
  • Thanks for the comment, I know the Object.assign and spread operator staff, they are not the same thing. but I would like to have the shortest way, better using ES6. – WangHongjian May 19 '22 at 10:16
  • 1
    Yet another way: `Object.fromEntries(input.map(x => [x,true]))`. – Felix Kling May 19 '22 at 10:20
  • [A simple loop?](https://jsfiddle.net/3a80vghm/) `const obj = {}; for (const key of arr) { obj[key] = true };`. – Andy May 19 '22 at 10:21

1 Answers1

1

You can do it using Array#Reduce

const arr = ["FirstName", "MiddleName", "LastName"]
const object = arr.reduce((acc, curr) => {
  acc[curr] = true
  return acc
}, {})

console.log(object)
RenaudC5
  • 3,553
  • 1
  • 11
  • 29