For more tips like this, sign up to the weekly newsletter!
Merge objects using Object.assign
When you work with objects, you might need to merge them, i.e. have an object that has all the properties from both sources.
Fortunately, ES6 brought a solution to this need. Before that, you had to iterate through the objects and assign the properties one by one. But now you can use Object.assign(target, sources...)
to merge.
The first argument is the target object; subsequent ones are the sources.
To merge an object into another one, use:
const dest = {a: 1};
const src = {b: 2};
Object.assign(dest, src);
// dest: {a: 1, b: 2}
The downside is it modifies the dest
object.
For a solution without side effects, create a new object to merge into:
const obj1 = {a: 1};
const obj2 = {b: 2};
const merged = Object.assign({}, obj1, obj2);
// merged: {a: 1, b: 2}
This way, the source objects are unchanged, making them safe to reuse.
On conflicting properties, the last object with the property wins:
const merged = Object.assign({}, {a: 1}, {a: 2});
// merged: {a: 2}