2

The new spread syntax can be used to elegantly merge several objects in the following way:

const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };

const summary = {...person, ...tools};

Is there a way to use this in a dynamical scenario, where the number and names of the objects to be merged are not known beforehand?

If

var objects_to_be_merged = get_objects();

generated an iterable list of objects during runtime, how can I use the spread operator iteratively to create a summary object like in the example above?

0

2 Answers 2

4

You can use Object.assign() with spread syntax to merge array of objects.

const person = { name: 'David Walsh', gender: 'Male' };
const tools = { computer: 'Mac', editor: 'Atom' };

const objects = () => [person, tools];
const summary = Object.assign({}, ...objects());
console.log(summary)

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

2 Comments

Worth noting that { ...[] } results in {}
Also, { ...{} } results in {}
2

Is there a way to use this in a dynamical scenario, where the number and names of the objects to be merged are not known beforehand?

Not with property spread notation*, no. Instead, you'd use Object.assign. If the number of objects is unknown, you'd pass it an array using (amusingly) array spread:

const combined = Object.assign({}, ...get_objects());

(Presumably get_objects() returns an array or other iterable.)


* property spread is a Stage 3 proposal at the moment, but it's supported without a runtime flag in current Chrome and Firefox and likely to be in ES2018. (Whereas array spread was in ES2015.)

Comments

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.