Home > Web Front-end > JS Tutorial > body text

How to Extract Specific Properties from an Array of Objects in JavaScript?

Linda Hamilton
Release: 2024-11-01 06:15:31
Original
569 people have browsed it

How to Extract Specific Properties from an Array of Objects in JavaScript?

How to Extract Specific Properties from an Array of Objects

In JavaScript, you may encounter scenarios where you possess an array of objects, each containing a substantial number of properties, but you only require a select few for further processing. This guide delves into techniques to extract these desired properties and create a new array comprising only those specified attributes.

To illustrate, consider the following hypothetical array of objects:

<code class="javascript">const dummyArray = [
    { "att1": "something", "att2": "something", /* … */, "att100": "something" },
    { "att1": "something", "att2": "something", /* … */, "att100": "something" },
    // …
];</code>
Copy after login

Method 1: Using Object Destructuring

Object destructuring allows you to extract specific properties from an object and assign them to new variables. By utilizing this technique, you can create a new array that contains only the desired properties:

<code class="javascript">const result = dummyArray.map(({ att20, att30, att70, att80 }) => ({
  att20, 
  att30, 
  att70, 
  att80
}));</code>
Copy after login

In this example, the map() method iterates over each object in the dummyArray and returns a new object with only the properties att20, att30, att70, and att80.

Method 2: Using the delete Operator

You can also selectively delete unwanted properties from each object and retain the desired ones:

<code class="javascript">const newDummyArray = dummyArray.map(function(item) { 
    delete item.att1; 
    // …
    return item; 
});</code>
Copy after login

In this approach, the delete operator is used to remove unwanted properties, leaving only the necessary ones in the modified array newDummyArray.

The above is the detailed content of How to Extract Specific Properties 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!