Object.assign keeps reference to original object

This question already has an answer here:

  • How do I correctly clone a JavaScript object? 54 answers

  • In fact this can be done in different ways:

  • Implement you own if you don't want external import, but take in consideration nested object. I implemented my own as follow (in case you have a nested object you need deep clone, so set deep=true ):
  • function cloneObj(obj, deep=false){
      var result = {};
      for(key in obj){
        if(deep && obj[key] instanceof Object){
           if(obj[key] instanceof Array){
             result[key] = [];
             obj[key].forEach(function(item){
                if(item instanceof Object){
                   result[key].push(cloneObj(item, true));
                } else {
                   result[key].push(item);
                }
             });
           } else {
             result[key] = cloneObj(obj[key]);
           }
        } else {
           result[key] = obj[key];
        }
      }
      return result
    }
    
    
    // Shallow copy
    var newObject = cloneObj(oldObject);
    // Deep copy
    var newObject = cloneObj(oldObject, true);
    
  • use jQuery :
  • // Shallow copy
    var newObject = jQuery.extend({}, oldObject);
    
    // Deep copy
    var newObject = jQuery.extend(true, {}, oldObject);
    
  • using UnderscoreJS:
  •  // Shallow copy
     var newObject = _.clone(oldObject);
    

    PS: I tested my function with the following data and works fine:

    var oldObject = {a:1, b:{d:2,c:6}, c:[1,2,{t:1}]};
    newObject= cloneObj(oldObject, true);
    
    newObject['b']['d']=8;
    newObject['a']=8;
    newObject['c'][2]['t']=5;
    
    
    console.log(oldObject)
    console.log(newObject)
    
    链接地址: http://www.djcxy.com/p/24770.html

    上一篇: Ecma6,Object.assign不会执行深层复制

    下一篇: Object.assign保持对原始对象的引用