JavaScript - check if array contains object with property equal to given value
In this article, we would like to show you how to check if array contains object with property equal to given value using JavaScript.
Quick solution:
xxxxxxxxxx
const array = [
{name: 'item-1'}
];
if (array.some((item) => item?.name === 'item-1')) {
// do something when item exists
}
or:
xxxxxxxxxx
const array = [
{name: 'item-1'}
];
const items = array.filter((item) => item?.name === 'item-1'); // finds multiple items
if (items.length > 0) {
// do something when items exists
}
Note: the solutions presented in this article were introduced in ES5.
It is good to use optional chaining to prevent errors when object or some property may be undefined
or null
.
Note: The optional chaining (
?.
) has been introduced in ES2020.
In this example, we use filter()
method to create a new array of items from users
array with name
property equal to the given value. If the length
of the new array is greater than 0
, it means that the array contains such an object.
xxxxxxxxxx
const users = [
{ name: 'Kate', age: 25 },
{ name: 'Tom', age: 23 },
{ name: 'Ann', age: 26 },
{ name: 'Jack', age: 21 }
];
if (users.filter(element => element?.name === 'Tom').length > 0) {
console.log('user found');
}
In this example, we use some()
method with optional chaining (?.
) to check if users
array contains at least one object with name
property equal to the given value.
xxxxxxxxxx
const users = [
{ name: 'Kate', age: 25 },
{ name: 'Tom', age: 23 },
{ name: 'Ann', age: 26 },
{ name: 'Jack', age: 21 }
];
if (users.some((item) => item?.name === 'Tom')) {
console.log('user found');
}
In this section, we present an alternative solution that works for older browsers.
xxxxxxxxxx
const users = [
{ name: 'Kate', age: 25 },
{ name: 'Tom', age: 23 },
{ name: 'Ann', age: 26 },
{ name: 'Jack', age: 21 }
];
if (users.filter(function(user) { return user.name === 'Tom'; }).length > 0) {
console.log('user found');
}