How to use Array.prototype.some() In Javascript
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
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:
Table of Content
- Iterative Approach
- Using Array.prototype.some()
Contact Us