Object.assign保持对原始对象的引用

时间:2015-12-18 03:21:38

标签: javascript babeljs

我有方法:

export const groupActivities = ({ activities, tags, images, tickets }) => {
  if (!activities || !tags) {
    console.error('Must have activities and tags');
  }

  const groupActivities = Object.assign({}, activities);

  const groups = groupByTags({ activities: groupActivities, tags });

  groups.forEach(group => {
    group.length = group.activities.length;
    console.log(group.length);
    group.activities.forEach(activity => {
      if (images) {
        activity.images = activity.imageIds.map(id => images[id]);
      }

      if (tickets) {
        console.warn('No tickets provided to the groupactivities helper. May cause problems.');
        activity.tickets = activity.ticketIds.map(id => tickets[id]);
      }
    });
  });

  return groups;
};

Object.assign正在复制活动对象,但仍然保留对它的引用,所以如果我找到一个特定的活动并在其上更改一些属性,它也会改变原始对象! (更改groupActivities ['someID']。name ='name'更改活动对象上的相应活动!)

这引起了一些奇怪的错误。任何解决方案?

使用babel 5进行编译。

1 个答案:

答案 0 :(得分:2)

事实上,这可以通过不同的方式完成:

  1. 如果您不想进行外部导入,请实现自己,但要考虑嵌套对象。我实现了自己的跟随(如果你有一个嵌套对象,你需要深度克隆,所以设置deep=true):
  2. 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);
    
    1. 使用 jQuery
    2. // Shallow copy
      var newObject = jQuery.extend({}, oldObject);
      
      // Deep copy
      var newObject = jQuery.extend(true, {}, oldObject);
      
      1. 使用UnderscoreJS
      2.  // Shallow copy
         var newObject = _.clone(oldObject);
        

        PS:我使用以下数据测试了我的功能并且工作正常:

        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)