Saturday, 20 May 2017

add a field and update another in array of objects

A query returns an array of objects from a collection. I want to add a field to each of the objects in that array, and update another field in every object of the array.

Products array before update:

[{ _id: 58d895b8ffc0346230a43a89,
  event: 'Junior Girls 12s',
  group: 'nonpro',
  price: 50,
  day: 'Friday' },
 { _id: 59d895b8ffc0346230a43a89,
  event: 'Junior Girls 14s',
  group: 'nonpro',
  price: 50,
  day: 'Friday', }]

My code to update the array of objects:

//add the field and changed price if late fee applies
for(var i = 0; i < products.length; i++) {
  products[i].field = registered.frifield;
  console.log(products[i].field);
  if(settings.latefeeamt > 0 && settings.frilatefee === true) { 
     products[i].price += settings.latefeeamt; 
  }
  console.log(products[i]);
  console.log(events.friday);
}

How products array SHOULD look after update:

[{ _id: 58d895b8ffc0346230a43a89,
  event: 'Junior Girls 12s',
  group: 'nonpro',
  price: 60,
  day: 'Friday',
  field: 'Main' },
 { _id: 59d895b8ffc0346230a43a89,
  event: 'Junior Girls 14s',
  group: 'nonpro',
  price: 60,
  day: 'Friday',
  field: 'Main' }]

How can I get this to work? It console.logs the correct field inside the loop, but I get the original array when it's done.



via user3561890

No comments:

Post a Comment