0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.