Created
February 16, 2020 02:55
-
-
Save IronGhost63/214d8c2ae0e14c61e53475bc87de429c to your computer and use it in GitHub Desktop.
Add or Update product
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
let products = [ | |
{ | |
id: 1, | |
quantity: 10, | |
}, | |
{ | |
id: 2, | |
quantity: 2, | |
} | |
]; | |
const add_product = ( products, new_item ) => { | |
let is_new = true; | |
products.map( item => { | |
if ( item.id === new_item.id ) { | |
item.quantity += new_item.quantity; | |
is_new = false; | |
} | |
return item; | |
} ); | |
if ( is_new ) { | |
products.push( new_item ); | |
} | |
return products; | |
} | |
// Try add existing product_id | |
products = add_product( products, { | |
id: 2, | |
quantity: 3, | |
} ); | |
console.log( products ); | |
// Try add new product_id | |
products = add_product( products, { | |
id: 3, | |
quantity: 3, | |
} ); | |
console.log( products ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment