How to use Array Filter Method In Javascript
In this approach, using the filter() method, we create a function findPropertyValue() to filter objects in the ‘objectsArray’ array based on a specific object id, returning an object property value in the form of a new array containing this particular object property that satisfies the specified condition.
Syntax:
array.filter(callback(element, index, arr), thisValue)
Example: The below code uses the JavaScript array filter method to find property values in an array of objects.
Javascript
const objectsArray = [ { id: 1, name: "w3wiki" }, { id: 2, name: "Computer Science" }, { id: 3, name: "Portal" }, { id: 4, name: "For Geeks" }, { id: 5, name: "GFG" }, ] function getPropertyValue(objectId) { const property = objectsArray.filter(object => object.id == objectId); if (property[0].name != null ) { //If-else condition return property[0].name; } else { return ; } } //Prints "name" property value of object with "id" 1 console.log(getPropertyValue(1)); |
w3wiki
How to Find Property Values in an Array of Object using if/else Condition in JavaScript ?
Finding property values in an array of objects using if/else condition is particularly useful when there is a collection of objects.
Table of Content
- Using Array Find Method
- Using Array Filter Method
- Using For Of Loop