Skip to content Skip to sidebar Skip to footer

Push To A New Array Inside A Map/promise

Here is a simplified version of my current setup. When running this code you'll notice that modifying the changes array also manipulates the original referrals array. Is this beca

Solution 1:

You just need to create a deep copy of the inner objects, you can do it with lodash deepClone, or spread operator.

Something like that:

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) {
  returnnewPromise(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);
});

Solution 2:

Thanks blex for walking me through what was going on here. Essentially when I was pushing the object to a new array, I was pushing the entire reference and not just a copy. Using Object.assign to clone the object solves my issue.

Here is the entire edit for reference:

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) {
  newPromise(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);
});

Post a Comment for "Push To A New Array Inside A Map/promise"