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 Answers 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);
answered Apr 12, 2018 at 12:42
gurvinder372
68.6k11 gold badges78 silver badges98 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Prawal Sharma
"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.
gurvinder372
That is the value returned by expression in () braces as output of every iteration. Please read up about reduce
Prawal Sharma
Thanks for the reply. Now i understood it completely.
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);
answered Apr 12, 2018 at 12:42
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
2 Comments
gurvinder372
Nice, didn't thought of using Object.assign myself +1
Prawal Sharma
Thanks for the quick reply. I also didn't gave a thought for this.
lang-js
strings.reduce( (a,c) => (a[c]=true, a), {})