1

I want to update one object from an array. This is my current working code which is updating the object inside the array

var equipment = this.equipments.find((e) => e.id === this.currentItem.id);

// this property is getting updated successfully in the array
equipment.countryId = this.currentItem.countryId;

But I have many properties in that object so I tried to use spread operator to fully copy the object to the existing object like this

var equipment = this.equipments.find((e) => e.id === this.currentItem.id);
equipment = { ...equipment, ...this.currentItem };

But this does not work. It does not update the object in the array.

Could be because the spread operator totally creates a new object and does not update the existing object?

Is there a way if not spread operator to update all the properties of the object with the new values without needing to explicitly write it for all properties?

Pawan Nogariya
  • 8,330
  • 12
  • 52
  • 105
  • 1
    Yes, it creates a new object entirely, which is **not** in the array. Typically this is done with something like `this.equipments = this.equipments.map((e) => needsEdit(e) ? { ...e, edited: true } : e)`. – jonrsharpe Jun 28 '22 at 11:01

1 Answers1

1

Could be because the spread operator totally creates a new object and does not update the existing object?

Yes, you need to return a new array and replace one element, it can be done using array.map:

this.equipments = this.equipments.map(equipment => {
    if(equipment.id === this.currentItem.id){
       return { ...equipment, ...this.currentItem };
    }
    return equipment;
});
mickl
  • 48,568
  • 9
  • 60
  • 89