Home >Web Front-end >JS Tutorial >How to Efficiently Extract a Property Value as an Array from an Array of Objects in JavaScript?
How to Extract Value of a Property as Array from an Array of Objects
In JavaScript, you may encounter situations where you need to extract a specific property value from each object in an array. One way to accomplish this is through a custom function, as shown below:
const objArray = [{ foo: 1, bar: 2 }, { foo: 3, bar: 4 }, { foo: 5, bar: 6 }]; function getFields(input, field) { const output = []; for (let i = 0; i < input.length; ++i) { output.push(input[i][field]); } return output; } const result = getFields(objArray, "foo"); // returns [ 1, 3, 5 ]
However, there are more concise and idiomatic approaches using JavaScript's array methods:
Array.prototype.map():
This method creates a new array with the results of calling a provided function on every element in the calling array. For your use case:
const result = objArray.map(a => a.foo);
Array.prototype.map() with Destructuring:
Using destructuring within the map function allows you to extract specific properties more concisely:
const result = objArray.map(({ foo }) => foo);
These methods provide a cleaner and more efficient way to extract property values without the need for custom functions.
The above is the detailed content of How to Efficiently Extract a Property Value as an Array from an Array of Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!