I have an array in the format below named cartarray.
1: {id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "90ドル", quantity: "1"}
2: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "43ドル", quantity: "3"}
3: {id: "1510-00-033-6312-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514540733034", name: "AIRPLANE UTILITY", price: "43ドル", quantity: "1"}
the html below is populated by the array above
cartarry.products.forEach(function(element) {
var id = element.id;
var itemname = element.name;
var itemprice = element.price;
var itemcard = `
<div class="product" id="${id}">
<div class="product-image">
<img src="https://s.cdpn.io/3/dingo-dog-bones.jpg">
</div>
<div class="product-details">
<div class="product-title">Dingo Dog Bones</div>
<p class="product-description"> ${itemname}</p>
</div>
<div class="product-price">${itemprice}</div>
<div class="product-quantity">
<input type="number" value="2" min="1">
</div>
<div class="product-removal">
<button class="remove-product">
Remove
</button>
</div>
<div class="product-line-price">25.98</div>
</div>
`;
itemcontainer.innerHTML += itemcard;
})
what I want to do is delete the clicked item from the array so I tried this
var items = cartarry.products;
$('.product').on('click', function(element) {
console.log(this.id)
var index = items.indexOf(this);
console.log(index)
var i = items.indexOf(this);
if (i != -1) {
items.splice(i, 1);
}
})
what I keep getting for index regardless of the item i clicked is -1 which keeps preventing the item from deleting. How can I fix this and delete clicked item from the array?
3 Answers 3
First of all you created an "item" object from "cartarry.products", you will not be able to delete the element from cartarry.products because you are deleting it from item, you can use this code to find an element by an specific property:
var index = cartarry.products.map(function(element) {
return element.id;
}).indexOf(this.id);
I created a plunkr example for you:
Comments
You won't find this in your array, because this is a DOM element.
You can search for the index of the item that contains your id instead, using Array.findIndex
var findId = this.id;
var match = items.findIndex(function (el) {
return el.id == findId;
});
if (match > -1) {
items.splice(match, 1);
}
Comments
$('.product').on(
'click',
({ id }) => cartarry.products = carrtarry.products.filter(pr => pr.id != id)
)
In your original code, this was the DOM element that was clicked, not your actual product. The above code takes the id from the clicked element and takes only the cartarry products that do not have the clicked id.