简体   繁体   中英

JavaScript - Updating multiple object values in array of objects

I try to change the values of multiple objects in an array of objects.

// for..of loop with variable i to access second array to get values

    const AntraegeListe = new Array();
for (let i = 0; i < MESRForm.MitarbeiterListe.length; i++) {
  AntraegeListe.push(obj);
}
  for (var i = 0; i < MESRForm.MitarbeiterListe.length; i++) {
  for (const _antrag of AntraegeListe) {
    _antrag.Mitarbeiter = MESRForm.MitarbeiterListe[i].Mitarbeiter;
    _antrag.UserIDMitarbeiter =
      MESRForm.MitarbeiterListe[i].UserIDMitarbeiter;
    _antrag.Vorgesetzter = MESRForm.MitarbeiterListe[i].Vorgesetzter;

    console.log(_antrag);
    break;
  }
}

console.log(AntraegeListe);

the values of the objects in the console.log are changed, but the Array is not changed iteratively. The Value that's being assigned to the objects in the array coming from another array (MitarbeiterListe[I].Mitarbeiter)

my expected output would be creating 3 array objects with values of another arrays values.

The solution for this was moving the object declaration inside the for loop and create new objects in the array on every iteration.

  createMESR(MESRForm: any): void {
const AntraegeListe = new Array();
for (var i = 0; i < MESRForm.MitarbeiterListe.length; i++) {
  var obj = {....};

  obj.AntragID = '';
  obj.Timestamp = '';
  obj.Antragsteller = MESRForm.Antragsteller;
  obj.Mitarbeiter = MESRForm.MitarbeiterListe[i].Mitarbeiter;
  ... 

  AntraegeListe.push(obj);
}

console.log(AntraegeListe);}

map function doesn't change the original array rather it creates a new array.

you can read this answer for more information:

https://stackoverflow.com/a/62341776/20801806

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM