Home  >  Article  >  Web Front-end  >  How to Add Properties to an Array of Objects Using Array.prototype.map()?

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

DDD
DDDOriginal
2024-10-23 11:49:30726browse

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'

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"

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>

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!

Statement:
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