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

How to Add Properties to an Array of Objects Using Array.prototype.map()?

DDD
Release: 2024-10-23 11:49:30
Original
802 people have browsed it

How to Add Properties to an Array of Objects Using Array.prototype.map()?

Adding a Property to an Array of Objects

In programming, arrays of objects are commonly used to represent data. Occasionally, it becomes necessary to add additional properties to the objects in these arrays.

Consider the following array of objects:

Object {
  Results: [Array[2]]
}
Results: [Array[2]]
[0-1]
0: Object
  id: 1
  name: "Rick"
1: Object
  id: 2
  name: 'david'
Copy after login

The goal is to add a new property named "Active" to each element of this array of objects, which should result in the following outcome:

Object {
  Results: [Array[2]]
}
Results: [Array[2]]
[0-1]
0: Object
  id: 1
  name: "Rick"
  Active: "false"
1: Object
  id: 2
  name: 'david'
  Active: "false"
Copy after login

To achieve this, one can utilize the Array.prototype.map() method. This method creates a new array by transforming each element of the original array using a provided mapping function.

<code class="javascript">Results.map(obj => ({ ...obj, Active: 'false' }))</code>
Copy after login

By utilizing the map() method, a new array of objects is created where each object has the additional "Active" property set to "false." This effectively adds the desired property to each element of the original array.

The above is the detailed content of How to Add Properties to an Array of Objects Using Array.prototype.map()?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template