On this, we’ll attempt to perceive that how we might extract the worth of a property as an array from an array of objects in JavaScript with the assistance of sure examples.
Pre-requisite: Array of Objects in JavaScript
Instance:
Enter: [ { apple: 2, mango: 4, }, { apple: 3, mango: 6, }, { apple: 7, mango: 11, }, ] Output: [2, 3, 7]
Rationalization:
- From an array containing a number of objects, we first have to pick on our personal the specified key.
- Thereafter selecting the specified key we must choose all of the values equivalent to the important thing in each object handed contained in the array.
- Thereafter in output, we’ve got to print the values equivalent to the important thing within the type of an array.
After understanding the specified process from the above instance, allow us to rapidly see the next approaches via which we might perceive in addition to clear up options for the above-shown process.
Method 1:
- A helper operate is created which consists of a parameter that’s our primary array of objects.
- Create a brief array contained in the operate during which outcomes shall be saved and printed later.
- Then utilizing the for-of loop, iterate over the values of that array of objects and thereafter choose values for the specified chosen key.
- Later after fetching values retailer these values in that non permanent array, return that worth from the operate, after which print it as an output.
Instance: Beneath is the implementation of the above-illustrated method.
Javascript
|
Output:
[ 2, 3, 7 ]
Method 2:
- A helper operate is created which consists of two parameters: the primary one is our primary array of objects and the second parameter is our desired key title.
- As illustrated within the earlier method, once more iterate over the array of objects, however this time map() operate of the array is used.
- Thereafter worth within the type of an array is returned.
Instance: Beneath is the implementation of the above method.
Javascript
|
Output:
[ 2, 3, 7 ]