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?

2 Answers 2

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.

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

Comments

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

4 Comments

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.
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.

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.