推送到地图/承诺中的新数组 [英] Push to a new array inside a map/promise

查看:62
本文介绍了推送到地图/承诺中的新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is a simplified version of my current setup.

运行此代码时,您会注意到修改 changes 数组也会操纵原始的 referrals 数组.这是因为我要在地图函数中 push changes 数组吗?如何修改 changes 数组而不修改 referrals 数组?

When running this code you'll notice that modifying the changes array also manipulates the original referrals array. Is this because I'm pushing to the changes array inside a map function? How can I modify the changes array without modifying the referrals array?

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或split运算符来完成它.

You just need to create a deep copy of the inner objects, you can do it with lodash deepClone, or 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);
});

这篇关于推送到地图/承诺中的新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆