Home >Web Front-end >JS Tutorial >How Can I Efficiently Extract Object Property Values into a New Array in JavaScript?
Extracting Object Property Values as an Array in JavaScript
When working with arrays of objects, a common task is to extract specific field values from each object and create an array of those values.
Naive Approach
A straightforward approach is to iterate over the array and push the desired property value into an output array:
function getFields(input, field) { var output = []; for (var i = 0; i < input.length; ++i) { output.push(input[i][field]); } return output; }
Elegant Solutions
However, there are more elegant and idiomatic ways to perform this task:
Array.map()
Array.map() is a built-in array method that transforms each element of the array using a provided callback function. This can be used to extract property values:
let result = objArray.map(a => a.foo);
Object Destructuring
If you need to extract multiple property values, you can use object destructuring within the map callback:
let result = objArray.map(({ foo }) => foo);
This approach is more concise and easier to read.
Notes:
The above is the detailed content of How Can I Efficiently Extract Object Property Values into a New Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!