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.
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.
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.
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.
In fact this can be done in different ways:
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);
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
// 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With