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 Efficiently Extract a Property Value as an Array from an Array of Objects in JavaScript?

Mary-Kate Olsen
Release: 2025-01-04 14:33:47
Original
802 people have browsed it

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 ]
Copy after login

However, there are more concise and idiomatic approaches using JavaScript's array methods:

  1. 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);
    Copy after login
  2. 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);
    Copy after login
  3. 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!

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