Open In App

How to extract value of a property as array from an array of objects ?

In this, we will try to understand that how we may extract the value of a property as an array from an array of objects in JavaScript with the help of certain examples.

Pre-requisite: Array of Objects in JavaScript



Example:

Input:
[
    {
        apple: 2,
        mango: 4,
    },
    {
        apple: 3,
        mango: 6,
    },
    {
        apple: 7,
        mango: 11,
    },
]
Output: [2, 3, 7]

Explanation:



After understanding the desired task from the above example, let us quickly see the following approaches through which we may understand as well as solve solutions for the above-shown task.

Approach 1:

Example: Below is the implementation of the above-illustrated approach.




let desiredValue = (fruits_quantity) => {
    let output = [];
    for (let item of fruits_quantity) {
        output.push(item.apple);
    }
    return output;
};
  
let fruits_quantity = [
    {
        apple: 2,
        mango: 4,
    },
    {
        apple: 3,
        mango: 6,
    },
    {
        apple: 7,
        mango: 11,
    },
];
  
let result = desiredValue(fruits_quantity);
console.log(result);

Output:

[ 2, 3, 7 ]

Approach 2:

Example: Below is the implementation of the above approach.




let desiredValue = (fruits_quantity, desired_key) => {
    let desiredValue = fruits_quantity.map((element) => element[desired_key]);
    return desiredValue;
};
  
let fruits_quantity = [
    {
        apple: 2,
        mango: 4,
    },
    {
        apple: 3,
        mango: 6,
    },
    {
        apple: 7,
        mango: 11,
    },
];
// Corresponding to this key values 
// (as an fruits_quantity) would be obtained...
let desired_key = "apple"
  
let result = desiredValue(fruits_quantity, desired_key);
console.log(result);

Output:

[ 2, 3, 7 ]

Article Tags :