JavaScript(JS) JS extract given property values from objects as array
https://www.theitroad.com
In JavaScript, you can extract the values of a given property from an array of objects as an array using the map()
method. Here's an example:
const users = [ { name: 'Alice', age: 30 }, { name: 'Bob', age: 40 }, { name: 'Charlie', age: 50 } ]; const ages = users.map(user => user.age); console.log(ages); // Output: [30, 40, 50]
In the above example, we first create an array of objects called users
, where each object represents a user and contains properties for name
and age
. We then use the map()
method to extract the values of the age
property from each object and return them as a new array called ages
. Finally, we log the ages
array to the console, which displays the values [30, 40, 50]
.
You can replace the age
property with any other property name to extract the values of that property from the objects in the array.