我有方法:
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进行编译。
答案 0 :(得分:2)
事实上,这可以通过不同的方式完成:
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:我使用以下数据测试了我的功能并且工作正常:
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)