以下是我当前设置的简化版本。
运行此代码时,您会注意到修改changes
数组也会操纵原始referrals
数组。这是因为我push
changes
在地图函数中的changes
数组?如何在不修改referrals
数组的情况下修改var referrals = [
{
id: 1,
name: 'John',
change: true
},
{
id: 2,
name: 'Sally',
change: false
},
{
id: 3,
name: 'Kim',
change: true
}
];
var changes = [];
var process = referrals.map(function(referral) {
return new Promise(function(resolve, reject) {
if (referral.change) {
changes.push(referral);
}
resolve();
});
});
Promise.all(process).then(function() {
console.log('referrals before:', referrals);
changes = changes.map(function(change) {
change.change_id = change.id;
delete change.id;
return change;
});
console.log('changes:', changes);
console.log('referrals after:', referrals);
});
数组?
#RevenueMTable tbody td
{
width: 72px !important;
}
#RevenueMTable tbody td.column0 {
width: 138px !important;
}

答案 0 :(得分:0)
您只需要创建内部对象的深层副本,您可以使用lodash deepClone或spread operator来完成。
类似的东西:
var referrals = [
{
id: 1,
name: 'John',
change: true
},
{
id: 2,
name: 'Sally',
change: false
},
{
id: 3,
name: 'Kim',
change: true
}
];
var changes = [];
var process = referrals.map(function(referral) {
return new Promise(function(resolve, reject) {
if (referral.change) {
changes.push({...referral}); // You will create a copy here.
}
resolve();
});
});
Promise.all(process).then(function() {
console.log('referrals before:', referrals);
changes = changes.map(function(change) {
change.change_id = change.id;
delete change.id;
return change;
});
console.log('changes:', changes);
console.log('referrals after:', referrals);
});
答案 1 :(得分:0)
感谢blex让我了解这里发生的事情。基本上当我将对象推送到一个新数组时,我正在推送整个引用,而不仅仅是一个副本。使用Object.assign
克隆对象解决了我的问题。
以下是整个编辑供参考:
var referrals = [
{
id: 1,
name: 'John',
change: true
},
{
id: 2,
name: 'Sally',
change: false
},
{
id: 3,
name: 'Kim',
change: true
}
];
var changes = [];
var process = referrals.map(function(referral) {
new Promise(function(resolve, reject) {
if (referral.change) {
changes.push(Object.assign({}, referral));
}
resolve();
});
});
Promise.all(process).then(function() {
console.log('referrals before:', referrals);
changes = changes.map(function(change) {
change.change_id = change.id;
delete change.id;
return change;
});
console.log('changes:', changes);
console.log('referrals after:', referrals);
});