Open In App

How to Check Presence of a Specific Object Property in an Array ?

Checking for the presence of a specific object property in an array involves determining whether any object within the array possesses the specified property. This task is commonly encountered when working with arrays of objects and needing to verify if a particular property exists across any of the objects in the array.

Below are the methods to check the presence of a specific property in an array:

Iterative Approach

In this approach, we iterate through the array and inspect each object individually to verify if the desired property exists. This method involves looping over each object and employing conditional statements to ascertain the presence of the property.

Example: The below code checks the presence of a specific object property in an array using the iterative approach in JavaScript.

function hasProperty(array, property) {
    for (let i = 0; i < array.length; i++) {
        if (array[i].hasOwnProperty(property)) {
            return true;
        }
    }
    return false;
}

const data = [
    { id: 1, name: "John" },
    { id: 2, name: "Alice", age: 25 },
    { id: 3, name: "Bob", city: "New York" }
];

console.log(hasProperty(data, "age")); 
console.log(hasProperty(data, "email")); 

Output
true
false

Using Array.prototype.some()

In this approach, we leverage the some() method provided by arrays to determine if at least one object within the array possesses the specified property. The some() method iterates through each element of the array until it encounters an object with the desired property.

Example: The below code check presence of a specific object property in an array using the Array.prototype.some() approach in JavaScript.

function hasProperty(array, property) {
    return array.some(obj => obj
        .hasOwnProperty(property));
}

const data = [
    { id: 1, name: "John" },
    { id: 2, name: "Alice", age: 25 },
    { id: 3, name: "Bob", city: "New York" }
];

console.log(hasProperty(data, "age"));
console.log(hasProperty(data, "email"));

Output
true
false
Article Tags :