How to Check If an Array Includes an Object in JavaScript

  145 views   2 months ago Javascript

Use the JavaScript some() Method

You can use the JavaScript some() method to find out if a JavaScript array contains an object.

This method tests whether at least one element in the array passes the test implemented by the provided function. Here's an example that demonstrates how it works:

<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>

 

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles