Skip to content Skip to sidebar Skip to footer

Object.assign Vs $.extend

Given that I am using an immutable object, I want to clone or copy an object in order to make changes. Now I have always been using javascript's native Object.assign but stumbled u

Solution 1:

The two key differences are the optional boolean for deep merge which is recursive on the jQuery $.extend method (where false is not supported?!) ...

let object1 = {
  id: 1,
  name: {
    forename: 'John',
    surname: 'McClane'
  },
};

let object2 = {
  id: 2,
  name: {
  }
};

// merge objects
let objExtend = $.extend(true, {}, object1, object2);
let objAssign = Object.assign({}, object1, object2);

// diff
console.log(objExtend.name.forename); // "John"
console.log(objAssign.name.forename); //  undefined

Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value.

Example: JsFiddle

The second is the $.extend method ignores undefined ...

let object1 = {
  id: 1,
  name: 'hello world'
};

let object2 = {
  id: 2,
  name: undefined
};

// merge objects
let objExtend = $.extend({}, object1, object2);
let objAssign = Object.assign({}, object1, object2);

// diff
console.log(objExtend.name); // "hello world"
console.log(objAssign.name); //  undefined

Example: JsFiddle

Docs

MDN: Object.assign(target, ...sources)

jQuery: jQuery.extend([deep], target, object1 [, objectN])

Additionally:

If you are looking for a way to deep merge objects without jQuery, this answer is excellent:

How to deep merge instead of shallow merge?

Example: JsFiddle

How to deep merge using Object.assign with ES6:

function isObject(item) {
  return (item && typeof item === 'object' && !Array.isArray(item));
}

function mergeDeep(target, ...sources) {
  if (!sources.length) return target;
  const source = sources.shift();

  if (isObject(target) && isObject(source)) {
    for (const key in source) {
      if (isObject(source[key])) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }
  return mergeDeep(target, ...sources);
}

Post a Comment for "Object.assign Vs $.extend"