Using a spread operator to combine objects
In a previous recipe, we saw how to use Object.assign to combine objects. It gets the job done, but by using newer ECMAScript syntax we can do this in a more compact way. In this recipe, we'll see how to use the new spread operator to combine objects.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
06-10-spread-operator-combine. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js. - Create a
main.jsfile with anasyncfunction namedmain, which creates a couple of objects and a constant. It then uses the spread operator and object structuring to combine them into a single object:
// main.js
export function main() {
const object1 = {
prop1: 'some value',
prop2: 'some other value',
} ...