简体   繁体   中英

Converting an Array into object in Javascript

I want to know the best way to convert an array in Js to object.

This is the sample of what i want to do. Input => ['abc', 'def']; Output => { abc: true, def: true }

I have done it using the code below. But just wanted to know if

**function toObject(strings) {
    var rv = {}
    strings.forEach(string => {
        rv[string] = true
    })
  return rv
}**

This function serves the purpose. But any experts out there with a best and efficient way possible.

Not sure what you mean by best and efficient way possible , since yours is alright according to me, this is a less versbose version

var output = strings.reduce( (a,c) => (a[c]=true, a), {})

Demo

 var strings = ['abc', 'def']; var output = strings.reduce( (a,c) => (a[c]=true, a), {}); console.log(output); 

You could map single objects and assign it to the same object.

 var array = ['abc', 'def'], object = Object.assign(...array.map(key => ({ [key]: true }))); console.log(object); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM