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.
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.
- 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.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file with anasync
function 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', } ...