JavaScript Program to Extract Given Property Values from Objects as Array
JavaScript is a versatile programming language that is widely used for web development. One of the most common tasks in JavaScript is to extract property values from an object and store them in an array.
In this article, we will discuss how to extract given property values from objects as an array using a hook. It's an easy job that can be done with a few lines of code.
We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Program to Extract Given Property Values from Objects as Array Using map()
In the code given below, the property's value of key a
is extracted from each object of an array.
map()
creates a new array from calling a function for every array element.
map()
calls a function once for each element in an array.
The map()
method is used to iterate through all the elements of an array and extract property values of key a
.
// JavaScript Program to extract value as an array from an array of objects
function extractValue(arr, prop) {
// extracting the value from property
let extractedValue = arr.map(item => item[prop]);
return extractedValue;
}
const objArray = [{a: 1, b: 2}, {a: 4, b: 5}, {a: 8, b: 9}];
const result = extractValue(objArray, 'a');
console.log(result);
[ 1, 4, 8 ]
Program to Extract Given Property Values from Objects as Array Using for Loop
In the code given below, the property value of key a
is extracted from each object of an array.
- Initially, the extractedValue array is empty.
- The
for
loop is used to iterate through all the elements of an array.
- During each iteration, the value of the property
a
is pushed to the extractedValue array.
// JavaScript Program to extract value as an array from an array of objects
function extractValue(arr, prop) {
let extractedValue = [];
for (let i=0; i < arr.length ; ++i) {
// extracting value from property
extractedValue.push(arr[i][prop]);
}
return extractedValue;
}
const objArray = [{a: 1, b: 2}, {a: 4, b: 5}, {a: 8, b: 9}];
const result = extractValue(objArray, 'a');
console.log(result);
[ 1, 4, 8 ]
Conclusion
To sum up, being able to extract provided property values from objects as an array is a typical task in JavaScript development. Adding a hook to our code will streamline this procedure and increase its efficiency.
The JavaScript code we've looked at so far allows us to send a collection of objects and a property name to a function, and it returns a collection of the values of that property in each object. This method eliminates the need for us to iteratively loop through the objects to get at their respective property values.