0

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?

Baz
  • 12,713
  • 38
  • 145
  • 268

2 Answers2

2

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 3
    [`...` is not an operator](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508). – Felix Kling Dec 15 '16 at 16:06
  • It is in MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator – Ori Drori Dec 15 '16 at 16:08
  • 2
    MDN is not the source of truth, the spec is. Please read the post I linked to. MDN actually changed the wording to "Spread syntax", but I guess URLs cannot be updated. – Felix Kling Dec 15 '16 at 16:09
  • It's not only the URL. They use it in the body as well several times. The link to the article is missing, but I'll your word for it. Changed to spread syntax. – Ori Drori Dec 15 '16 at 16:27