javascript
How to Check If an Array Includes an Object
<script>
// An array of objects
var persons = [{name: "Harry"}, {name: "Alice"}, {name: "Peter"}];
// Find if the array contains an object by comparing the property value
if(persons.some(person => person.name === "Peter")){
alert("Object found inside the array.");
} else{
alert("Object not found.");
}
</script>
Note that if try to find the object inside an array using the indexOf() method like persons.indexOf({name: "Harry"}) it will not work (always return -1). Because, two distinct objects are not equal even if they look the same (i.e. have the same properties and values). Likewise, two distinct arrays are not equal even if they have the same values in the same order.
The some() method is supported in all major browsers, such as Chrome, Firefox, IE (9 and above), etc. See the tutorial on JavaScript ES6 Features to learn more about arrow function notation.
Was this helpful?
Similar Posts
- Check if Array includes String(Case Insensitive) Javascript
- Check if string includes a substring Javascript (Multiple Methods)
- How to Check if Arrays in a Object Are All Empty
- Convert object {key: value} to Array [[key, value]] Javascript
- Get all values as array items from an Object in Javascript
- Lodash - Convert paired Array to key value paired object
- Prettify JSON object or array using JSON.stringify