Home > Web Front-end > JS Tutorial > How Can I Efficiently Extract Property Values from an Array of Objects into a New Array?

How Can I Efficiently Extract Property Values from an Array of Objects into a New Array?

Mary-Kate Olsen
Release: 2024-12-29 12:43:10
Original
158 people have browsed it

How Can I Efficiently Extract Property Values from an Array of Objects into a New Array?

From an Array of Objects, Efficiently Extract Property Values as an Array

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);
Copy after login

Alternatively, a slightly more concise and semantically expressive syntax can be utilized:

let result = objArray.map(({ foo }) => foo);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template