Baz
Baz

Reputation: 13135

Object from array using es6

I would like to have this object:

const m = {a:undefined, b:undefined, d:undefined};

but would prefer to produce it from an array:

const m = {}
const l = ["a","b","c"];
for (const i in l){
    m[l[i]] = undefined;
}

But what would be a nicer way of doing this when using es6?

Upvotes: 0

Views: 76

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

You can Array#map each property to an object, and combine them using the spread syntax, and Object#assign:

const m = Object.assign(...['a', 'b', 'c'].map((prop) => ({ [prop]: undefined })));

console.log(m);

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816442

You could use for/of, but Array#reduce (which exists since ES5) might be more elegant:

const m = ['a', 'b', 'c'].reduce((o, k) => (o[k] = undefined, o), {});

However, if you need this a lot, I'd recommend to create a reusable function with a proper name.

Upvotes: 2

Related Questions