Home  >  Article  >  Web Front-end  >  How to Add a New Property to Each Object in an Array Using JavaScript?

How to Add a New Property to Each Object in an Array Using JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 12:04:01425browse

How to Add a New Property to Each Object in an Array Using JavaScript?

Augmenting Objects in an Array

Within an array of objects, adding an additional property to each object requires programming techniques to ensure each object contains the new property. Consider the following scenario:

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 an "Active" property to each element, resulting in:

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 accomplish this, you can apply the Array.prototype.map() method:

Results.map(obj => ({ ...obj, Active: 'false' }))

The map() method iterates through each object (obj) in the Results array and returns a new array with the transformed objects. Within the arrow function, you spread the properties of the original object (...obj) and add the new "Active" property with the value "false." This ensures each new object contains all the existing properties plus the "Active" property.

Refer to the MDN documentation for further details on Array.prototype.map(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The above is the detailed content of How to Add a New Property to Each Object in an Array Using JavaScript?. 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