Object.assign()

TheObject.assign()method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Object.assign(target, ...sources)
var obj = { a: 1 };
var copy = Object.assign({}, obj);

Merging objects

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed.

Merging objects with same properties

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

results matching ""

    No results matching ""