1

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);
}
Abu Nooh
  • 846
  • 4
  • 12
  • 42
  • 1
    `items[index].quantity = 2` – Reactgular Apr 25 '19 at 21:48
  • 1
    If `name` is unique shouldn't `items` be an object keyed to `name`? That would make this problem go away. – Mark Apr 25 '19 at 21:49
  • @cgTag that solved it, thank you! Could accept as answer would be appreciated if you could explain if I'd run into any browser compatibility issues as well. – Abu Nooh Apr 25 '19 at 21:58
  • No browser issues here, and this was a syntax mistake so I'd rather not post an answer. – Reactgular Apr 25 '19 at 22:01
  • Possible duplicate of [Array.push() if does not exist?](https://stackoverflow.com/questions/1988349/array-push-if-does-not-exist) – Striped Apr 25 '19 at 22:19

1 Answers1

6

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);
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79