1

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.

2
  • 3
    strings.reduce( (a,c) => (a[c]=true, a), {}) Commented Apr 12, 2018 at 12:41
  • Your function itself is good enough. Commented Apr 12, 2018 at 12:45

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

"a[c]=true" - I understood this part. But can you please explain me the second part - ",a". All in all i want to know what this second parameter is doing after comma (a[c]=true, a). Is this assigning value in a.
That is the value returned by expression in () braces as output of every iteration. Please read up about reduce
Thanks for the reply. Now i understood it completely.
1

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

2 Comments

Nice, didn't thought of using Object.assign myself +1
Thanks for the quick reply. I also didn't gave a thought for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.