update all objects in an array
outbackStack opened this issue · comments
outbackStack commented
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;
});
outbackStack commented
the following code will update the array:
const updateAll = produce(shoppingCart, (draft) => {
for (const el of draft.docLines) {
el.total = el.qty * el.price;
}
});