Prawal Sharma
Prawal Sharma

Reputation: 21

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.

Upvotes: 1

Views: 79

Answers (2)

gurvinder372
gurvinder372

Reputation: 68433

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);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386848

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);

Upvotes: 1

Related Questions