0

Trying to mutate objects in a for loop.

I am expecting console.log(dish) to log the dish object with an ingredients property containing an array of unshifted ingredients.

When I log dish.ingredients, it logs the ingredients.

When I log dish, it logs the dish objects without the ingredients.

Why is this?

for (let dish of dishArray) {
  dish['ingredients'] = []
  for (let ingredient of ingredientsArray) {
    if (dish._id.equals(ingredient._dishID)) {
      dish['ingredients'].unshift(ingredient)
    }
  }
  console.log(dish['ingredients'])             <------------- 
  console.log(dish)                            <-------------         
}

dishArray is an array of dish objects returned from a mongoose query.

softcode
  • 4,358
  • 12
  • 41
  • 68

1 Answers1

0

Without further knowledge of your code, plain javascript == will do the job

var dishArray = [{
  _id: '0'
}, {
  _id: '1'
}];
var ingredientsArray = [{
  _id: '0',
  _dishID: '0'
}, {
  _id: '1',
  _dishID: '1'
}];

for (let dish of dishArray) {
  dish['ingredients'] = [];

  for (let ingredient of ingredientsArray) {
    if (dish._id == ingredient._dishID) {
      dish['ingredients'].unshift(ingredient);
    }
  }

  console.log(dish['ingredients']);
  console.log(dish);
}
rdlopes
  • 661
  • 4
  • 11
  • turns out it's the returned mongoose object that doesn't play friendly with mutations – softcode Feb 20 '17 at 03:12
  • Then maybe you could try to lean() or toObject() your Mongoose object, by following the provided answer here: http://stackoverflow.com/questions/7503450/how-do-you-turn-a-mongoose-document-into-a-plain-object – rdlopes Feb 20 '17 at 03:17