JS: Object.assign (merge objects)

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

Object.assign

Object.assign(target_obj, source_obj_1, source_obj_2, etc)
  • Merge all source object keys into target object. (by shallow copy †)
  • Only Enumerable own properties are considered.
  • If property keys clash, later sources overwrites earlier ones.
  • target_obj is modified.
  • Return target_obj.

† Shallow copy means, if a source object contains a key whose value is object xobj, the result will have xobj as a reference, not creating new object, meaning, if xobj is modified, it'll show up in both source and result object.

// merge objects into one

const aa = { cat: 0 };
const bb = { cat: 14 };
const cc = { dog: 79 };
const xx = Object.assign(aa, bb, cc);
console.log(xx);
// { cat: 14, dog: 79 }

// original modified
console.log(xx === aa);
// true

Example. shallow copy of object value.

// example. shadow copy of object value.

const aa = { bird: 0 };
const xx = Object.assign({ dog: 1 }, { animal: aa });

console.log(xx);
// { dog: 1, animal: { bird: 0 } }

// change a key in aa
aa.bird = 9;

console.log(aa);
// { bird: 9 }

// xx also changed
console.log(xx);
// { dog: 1, animal: { bird: 9 } }