How to Find Property Values in an Array of Object using if/else Condition in JavaScript ?
Last Updated :
17 Jul, 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) { //If-else condition
return object.name;
}
else {
return null;
}
}
// Prints "name" property value of object with "id" 2
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) { //If-else condition
return property[0].name;
}
else {
return;
}
}
//Prints "name" property value of object with "id" 1
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) { //If-else condition
return obj.name;
} else {
continue;
}
}
return null;
}
//Prints "name" property value of object with "id" 3
console.log(getPropertyValue(3));
Using Array Map Method
Another useful approach to find and transform property values in an array of objects is by utilizing the map() method. The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. This can be particularly useful for extracting or transforming specific property values.
Example: In this example, we use the map() method to find and transform property values in an array of objects. The function findAndTransformPropertyValue() takes an array of objects and a specific property name, then returns a new array containing the values of the specified property for each object.
JavaScript
function findAndTransformPropertyValue(objectsArray, propertyName) {
return objectsArray.map(obj => obj[propertyName]);
}
const objectsArray = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
];
const names = findAndTransformPropertyValue(objectsArray, 'name');
console.log(names); // Output: ['Alice', 'Bob', 'Charlie']
const ages = findAndTransformPropertyValue(objectsArray, 'age');
console.log(ages); // Output: [25, 30, 35]
Output[ 'Alice', 'Bob', 'Charlie' ]
[ 25, 30, 35 ]
Using Array Reduce Method
The reduce method executes a reducer function on each element of the array, resulting in a single output value. This method can be particularly useful for aggregating or accumulating property values based on certain conditions.
Example: The following code demonstrates how to use the JavaScript reduce method to find a property value in an array of objects. We create a function findPropertyValueUsingReduce() that accumulates the desired property value based on a specific object ID.
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 findPropertyValueUsingReduce = (objectId) => {
return objectsArray.reduce((accumulator, currentObject) => {
if (currentObject.id === objectId) { // If-else condition
return currentObject.name;
}
return accumulator;
}, null);
};
// Prints "name" property value of object with "id" 4
console.log(findPropertyValueUsingReduce(4));
Using Array Some Method
The some method tests whether at least one element in the array passes the provided test function. This can be useful for finding a property value and stopping the search as soon as the condition is met.
Example: The following code demonstrates how to use the JavaScript some method to find a property value in an array of objects. We create a function findPropertyValueUsingSome() that returns the property value of an object based on a specific object ID if it exists.
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 findPropertyValueUsingSome = (objectId) => {
let result = null;
objectsArray.some(object => {
if (object.id === objectId) { // If-else condition
result = object.name;
return true;
}
return false;
});
return result;
};
console.log(findPropertyValueUsingSome(5));
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read