Reputation: 47
I have an array of object like so
[{name: "Apple", price: "10", quantity: "1"},{name: "Dog", price: "55", quantity: "2"},{name: "Car", price: "88", quantity: "4"},]
etc How do I determine if for example my 2. object's name == Dog?
My IRL Example is this: I have a shopping cart and I don't want to add the same product twice
const handleAddToCart = (product)=>{
console.log(inCart)
if(!inCart.includes(product)){
product.quantity = product.quantity+1;
setInCart(inCart.concat(product));
}
}
InCart is my array of object and product is 1 object from the array The above version is not good because I update the quantity property and after I reset the page it will add multiply times
Upvotes: 0
Views: 46
Reputation: 89204
You can use Array#some
to check if there is already an object with a specific name.
let name = "Dog";
let hasDuplicate = inCart.some(x => x.name === name);
For increased performance, consider storing a Set
of names for constant-time lookup.
Upvotes: 1