immerjs / immer

Create the next immutable state by mutating the current one

Home Page:https://immerjs.github.io/immer/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

update all objects in an array

outbackStack opened this issue · comments

Is there a way to update all the object totals in this array if the price or quantity changes? I can only update one but I'm trying to figure how to loop through docLines.

// object mutations
const shoppingCart = {
  docLines: [
    { name: "Apple", qty: 2, price: 1, total: 2 },
    { name: "Orange", qty: 1, price: 5, total: 5 },
  ],
};

// update docLines
const updateAll = produce(shoppingCart, (draft) => {
  draft.docLines[0].total =  draft.docLines[0].qty * draft.docLines[0].price;
});

the following code will update the array:

const updateAll = produce(shoppingCart, (draft) => {
  for (const el of draft.docLines) {
    el.total = el.qty * el.price;
  }
});