Given an array of objects with a specific structure, one may desire to extract and assemble the values of a particular property into a singular array. While one approach involves employing a custom utility function, this method requires iteration and manual population of the target array.
A more refined and idiomatic approach leverages the map() method, offered by Array.prototype. This method facilitates the seamless application of a function to each element within an array, generating a new array with the transformed elements. In this case, the desired function would extract the target property's value.
For example, to extract the "foo" property values from the provided object array, the map() method can be employed as follows:
let result = objArray.map(a => a.foo);
Alternatively, a slightly more concise and semantically expressive syntax can be utilized:
let result = objArray.map(({ foo }) => foo);
By employing the map() method, the creation of a custom utility function becomes unnecessary, yielding a more concise and elegant solution. Refer to Array.prototype.map() for further exploration and utilization scenarios.
The above is the detailed content of How Can I Efficiently Extract Property Values from an Array of Objects into a New Array?. For more information, please follow other related articles on the PHP Chinese website!