Created
February 7, 2019 09:52
-
-
Save ahmedsadman/aecbeb2ca7c9d9f572dbf80838f61869 to your computer and use it in GitHub Desktop.
Javascript immutable way of updating shopping cart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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