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.htmlthat loads and runs amainfunction frommain.js. - Create a
main.jsfile with amainfunction that creates two objects, and then usesObject.assignto combine them with another anonymous object:
// main.js
export function main() {
const object = {};
const otherObject = {
foo: 'original value',
bar: 'another value'
}
Object.assign(object...