Languages
[Edit]
EN

JavaScript - check if array contains object with property equal to given value

0 points
Created by:
Wayne
475

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:

or: 

Note: the solutions presented in this article were introduced in ES5.

 

Practical examples

Edit

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.

1. Using Array filter() method

Edit

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.

2. Using Array some() method

Edit

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.

Solution for older browsers

Edit

In this section, we present an alternative solution that works for older browsers.

 

See also

Edit
  1. How to use optional chaining in JavaScript ES2020?

  2. JavaScript - basic array operations (map, filter, find, fill, some, every methods)

References

Edit
  1. Array.prototype.filter() - JavaScript | MDN
  2. Array.prototype.some() - JavaScript | MDN
  3. Optional chaining (?.) - JavaScript | MDN

Alternative titles

  1. JavaScript - determine if array contains object with attribute that equals given value
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join