0

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 }
];
King Rayhan
  • 2,287
  • 3
  • 19
  • 23
  • May I know your primary key for compare? product_id or product_name? – Kai Mar 01 '18 at 05:12
  • 1
    Iterate over the list and if you find the productId add quatity and if not, add object to list. For this purpose maybe it will better another structure like a dictionary with the productId as key and the rest as value – jonhid Mar 01 '18 at 05:12
  • @kai yes, `product_id` is the main key here for comparing – King Rayhan Mar 01 '18 at 05:14
  • Iterate over a list of 3 products is OK but what happens if you have thousands of them? – jonhid Mar 01 '18 at 05:27
  • How it is Duplicate ? Since it is totally different question from my point of view. – Legend Mar 10 '18 at 04:01

5 Answers5

4

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 }
];

function addProduct(product){
  var found = false;
  for( index in bags){
    if(bags[index].product_id == product.product_id){
        bags[index].quantity += product.quantity;
        found = true;
        break;
    }
  }
  if(!found){
    bags.push(product);
  }
}

var data = { product_id: 1 , product_name: "product 1" , quantity: 3 };

addProduct(data);
console.log(bags);
data = { product_id: 10 , product_name: "product 1" , quantity: 3 };
addProduct(data);
console.log(bags);
Lalit
  • 1,354
  • 1
  • 8
  • 13
  • It works for me, Thanks, man :) – King Rayhan Mar 01 '18 at 05:20
  • Missing explanation. -1. Also, for such obvious questions, please chose to look for a similar link and close it as dupe. We are here to help and not do someone else's job for free. – Rajesh Mar 01 '18 at 05:26
  • @MuhammadRayhan I have updated the code. Added return statement to break out of loop. – Lalit Mar 01 '18 at 05:27
  • @Rajesh Thanks for reminding me. Just going to do that. – Lalit Mar 01 '18 at 05:27
  • `return; // to break out of loop` Did you check if it actually does? – Rajesh Mar 01 '18 at 05:27
  • @Rajesh I will update the answer. Thank you for pointing out the issue. – Lalit Mar 01 '18 at 05:30
  • @Lalit This will help you: https://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add – Rajesh Mar 01 '18 at 05:31
  • @Lalit Thanks for your help, I appreciate your kindness, Can you help me once more time, please? When product_id will not match , then push new item to the bags array, how do I do that? – King Rayhan Mar 01 '18 at 05:31
  • @MuhammadRayhan See above comment by Rajesh its cleaner approach then what I have used. – Lalit Mar 01 '18 at 05:35
  • @MuhammadRayhan Sorry for being rude, but this is not **Get code for free site**. Lalit has showed you the way. Please try to achieve on your own. – Rajesh Mar 01 '18 at 05:36
  • @Lalit Thanks! This is the reason I prefer marking posts as dupe instead. You do not have enough rep but you will someday. Please chose to close such post instead of answering. – Rajesh Mar 01 '18 at 05:37
2

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 }
        ];    
var data = { product_id: 1 , product_name: "product 1" , quantity: 3 };

bags.map(obj => {
    if(obj.product_id == data.product_id && data.hasOwnProperty('quantity')) {
       obj.quantity += data.quantity;
       return; // Break the loop
    }
});

console.log(bags);
King Rayhan
  • 2,287
  • 3
  • 19
  • 23
Sudhakar Lahane
  • 137
  • 1
  • 2
  • 12
1

you can implement a new prototype of Array ( or simply create a new function) to compare before push. And as far as I know there is new prototype function of Array called find and it helps.

Array.prototype.updatePush = function(obj) {
    const foundItem = this.find((item) =>item.product_id === obj.product_id);
    if (foundItem) {
        foundItem.quantity += obj.quantity;
    } else { 
        this.push(obj);
    }
}
    
bags.updatePush({ product_id: 1 , product_name: "product 1" , quantity: 3 }); // the product_id 1 object should be updated.
Piran
  • 7,180
  • 1
  • 24
  • 37
Kai
  • 3,104
  • 2
  • 19
  • 30
0

Do you have to use an array for this? This is a perfect case for using objects as maps. Just use the product_id as the key for your object. Very easy to search.

var bags = {
    1: { product_id: 1 , product_name: "product 1" , quantity: 1 },
    2: { product_id: 2 , product_name: "product 3" , quantity: 1 },
    3: { product_id: 3 , product_name: "product 2" , quantity: 1 }
}

function addProduct(bags, product) {
    var product_id = product.product_id;
    if (product_id in bags) {
        // it's already a product, update quantity
        bags[product_id].quantity += product.quantity;
    } else {
        // it's not a product, add it.
        bags[product_id] = product
    }
}

addProduct(bags, { product_id: 1 , product_name: "product 1" , quantity: 3 })

console.log(bags[1])
// { product_id: 1, product_name: 'product 1', quantity: 4 }
SCB
  • 5,821
  • 1
  • 34
  • 43
  • Please chose to close such posts as duplicate. This questions has been answered more than once – Rajesh Mar 01 '18 at 05:20
-3

You need to somehow identify the object you want to update. For the case of updating first object:

bags[0].quantity = 4;

Ruhshan
  • 121
  • 1
  • 8