Skip to content

Instantly share code, notes, and snippets.

@IronGhost63
Created February 16, 2020 02:55
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 IronGhost63/214d8c2ae0e14c61e53475bc87de429c to your computer and use it in GitHub Desktop.
Save IronGhost63/214d8c2ae0e14c61e53475bc87de429c to your computer and use it in GitHub Desktop.
Add or Update product
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