Using Object.assign to add properties to an object
Combining the properties from different objects is a fairly common task. Doing this value by value is limited and tedious, because each property has to be enumerated. This recipe demonstrates how to do the same thing with the Object.assign
method.
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-01-object-assign-add-properties
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file with amain
function that creates two objects, and then usesObject.assign
to combine them with another anonymous object:
// main.js export function main() { const object = {}; const otherObject = { foo: 'original value', bar: 'another value' } Object.assign(object...