Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object.assign keeps reference to original object [duplicate]

I have method:

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 is copying the activities object, but still keeps references to it, so if I find a specific activity and change some property on it, it changes the original too! (changing groupActivities['someID'].name = 'name' changes the corresponding activity on activities object!)

This is causing some weird bugs. Any solution?

Using babel 5 for compiling.

like image 655
Mohamed El Mahallawy Avatar asked Dec 18 '15 03:12

Mohamed El Mahallawy


People also ask

Does object assign keep reference?

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.

Does object assign do a deep copy?

Object. assign does not copy prototype properties and methods. This method does not create a deep copy of Source Object, it makes a shallow copy of the data. For the properties containing reference or complex data, the reference is copied to the destination object, instead of creating a separate object.

Does object assign return new object?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.


1 Answers

In fact this can be done in different ways:

  1. 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);
  1. use jQuery:
// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
  1. 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)
like image 104
Dhia Avatar answered Oct 11 '22 15:10

Dhia