Abu Nooh
Abu Nooh

Reputation: 856

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

Upvotes: 1

Views: 5344

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44105

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

Upvotes: 6

Related Questions