How to Find Property Values in an Array of Object using if/else Condition in JavaScript ?
Last Updated :
30 Jan, 2024
Finding property values in an array of objects using if/else condition is particularly useful when there is a collection of objects.
The array find method loop in JavaScript is used to retrieve the first element in an array that satisfies a given condition. In this approach, using the find() method, we create a function findPropertyValue() to filter objects in the ‘objectsArray’ array based on a specific object id, returning an object property value.
Syntax:
array.find(function(currentValue, index, arr), thisValue)
Example: The below code uses the JavaScript array find method to find property values in an array of objects.
Javascript
const objectsArray = [
{ id: 1, name: "GeeksforGeeks" },
{ id: 2, name: "Computer Science" },
{ id: 3, name: "Portal" },
{ id: 4, name: "For Geeks" },
{ id: 5, name: "GFG" },
]
const findPropertyValue = (objectId) => {
const object =
objectsArray.find((object) => object.id === objectId);
if (object) {
return object.name;
}
else {
return null ;
}
}
console.log(findPropertyValue(2));
|
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: "GeeksforGeeks" },
{ 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 ) {
return property[0].name;
}
else {
return ;
}
}
console.log(getPropertyValue(1));
|
In this approach, we create a function findPropertyValue() using a for-of loop to iterate through objects based on a specific object ID, searching for a property’s value accordingly. The matching object property value is returned as the output.
Example: The below code uses the JavaScript for-of loop to find property values in an array of objects.
Javascript
const objectsArray = [
{ id: 1, name: "GeeksforGeeks" },
{ id: 2, name: "Computer Science" },
{ id: 3, name: "Portal" },
{ id: 4, name: "For Geeks" },
{ id: 5, name: "GFG" },
]
function getPropertyValue(objectID) {
for (const obj of objectsArray) {
if (obj.id == objectID) {
return obj.name;
} else {
continue ;
}
}
return null ;
}
console.log(getPropertyValue(3));
|
Share your thoughts in the comments
Please Login to comment...