Skip to content

Instantly share code, notes, and snippets.

@ahmedsadman
Created February 7, 2019 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedsadman/aecbeb2ca7c9d9f572dbf80838f61869 to your computer and use it in GitHub Desktop.
Save ahmedsadman/aecbeb2ca7c9d9f572dbf80838f61869 to your computer and use it in GitHub Desktop.
Javascript immutable way of updating shopping cart
/*
Javascript: Immutable way of changing quantity in a shopping cart
*/
let cart = [{
id: 1,
quantity: 3
},
{
id: 2,
quantity: 4
},
{
id: 3,
quantity: 10
}
];
const itemID = 2; // item id that should be changed
let modifiedCart = cart.map((item) => {
if (item.id === itemID) {
return {
...item,
quantity: 1
}
}
return item;
});
modifiedCart.forEach(val => console.log(val));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment