JS: Object.assign (merge objects, copy properties)

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

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.
  • Return the modified 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 = { k99: 0 };
const bb = { k3: 0 };
const cc = { k6: 0 };

const xx = { k99: 1 };

const xresult = Object.assign(xx, aa, bb, cc);

console.log(xresult);
// { k99: 0, k3: 0, k6: 0 }

// original modified, same as result
console.log(xx === xresult);
// true