Search code examples
javascriptjquerymultidimensional-arrayarray-push

Javascript update array value if exists otherwise push new array to object


I am trying to update a value in the array if it is found, if it isn't then add a new array to it.

Here's some code I have been trying:

var cartItems = {};
var items = []
cartItems.items = items;
$('.proAdd').click(function(){
var name = $(this).attr("data-name");
var price = parseFloat($(this).attr("data-price"));
var quantity = parseInt($(this).attr("data-quantity"));

var item = {"name": name,"price": price,"quantity": quantity}

items.forEach(function(item) {
if (item.name === name) {
item.quantity = 2
return; 
}else{
cartItems.items.push(item);
}
});

In this version noting gets pushed. If I take out the else branch then it does update it but also pushes it. I have created a fiddle for this.

Also tried this but it says x.quantity is not defined:

var index = items.findIndex(x => x.name==name)
if (index != -1){
x.quantity = 2
}
else {
cartItems.items.push(item);
}

Solution

  • Because index stores the index of an item, and x is a temporary value which is unavailable after that line. Use find instead, and make sure you're looking at the same items each time:

    var item = cartItems.items.find(x => x.name == name);
    if (item) {
      item.quantity = 2;
    } else {
      cartItems.items.push(item);
    }