I have an array of object of products, which includes several products details.
var bags = [
{ product_id: 1 , product_name: "product 1" , quantity: 1 },
{ product_id: 2 , product_name: "product 3" , quantity: 1 },
{ product_id: 3 , product_name: "product 2" , quantity: 1 }
];
I can push new array here like this,
bags.push({ product_id: 4 , product_name: "product 4" , quantity: 1 });
Now I need when I will push a new object in this array, if that new object's product_id
is already there then instead of adding new item, at already existed product's quantity, will increase.
Suppose I will add this object to bags
array which is already existed in the array previously.
{ product_id: 1 , product_name: "product 1" , quantity: 3 }
Now instead of creating new item, I need My bags
array will look like this
var bags = [
{ product_id: 1 , product_name: "product 1" , quantity: 4 }, // <- updated
{ product_id: 2 , product_name: "product 3" , quantity: 1 },
{ product_id: 3 , product_name: "product 2" , quantity: 1 }
];