Update one object of an array using spread operator not working

Viewed 62

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?

1 Answers

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;
});

Related