gpt4 book ai didi

javascript - 推送到 map / promise 内的新数组

转载 作者:行者123 更新时间:2023-11-28 04:17:16 25 4
gpt4 key购买 nike

这是我当前设置的简化版本。

运行此代码时,您会注意到修改 changes 数组也会操作原始 referrals 数组。这是因为我正在 pushing 到 map 函数内的 changes 数组吗?如何在不修改 referrals 数组的情况下修改 changes 数组?

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);
});

最佳答案

您只需要创建内部对象的深拷贝,可以使用 lodash deepClone 或 spread 运算符来完成。

类似的事情:

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);
});

关于javascript - 推送到 map / promise 内的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45721828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com