Check if an array of objects contains a certain key-value in JavaScript
The other day, I was stumbled upon a scenario where I need to check whether there exists at least one key of a certain value in an array of objects.
Check the following for example.
const products = [
{
id: 1,
name: "Cereal",
category: "food"
},
{
id: 2,
name: "Shampoo",
category: "grocery"
},
{
id: 3,
name: "Fruit jam",
category: "food"
}
];
As you can tell, we have an array of objects called products
and now let’s say, we want to check if this array has at least one object that has category
set as “grocery”.
Turns out, it’s pretty easy to check this using the Array.prototype.some() method.
The some()
method to the rescue
Quoting from MDN,
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn’t modify the array.
So, if we want to check if the products
array has at least one object that has category
set as “grocery”, we can do it through the some()
method like so.
const hasGrocery = products.some(function(product) {
return product.category === 'grocery';
})
console.log(hasGrocery);
// outputs: true
As you can tell, the some()
method accepts a callback as its argument from which we can return the condition. Based on the truthiness of this condition, the some()
method will return true
or false
.
In our example, it will return true
since the array contains an object that has category
set as “grocery”. And that’s exactly what I wanted to check!
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.