简体   繁体   中英

How to determine if my array of object has an attribute with a specific value

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM