Object.assign vs $.extend

后端 未结 1 485
青春惊慌失措
青春惊慌失措 2021-01-31 06:58

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 jav

1条回答
  •  北海茫月
    2021-01-31 07:35

    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);
    }
    

    0 讨论(0)
提交回复
热议问题