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

How to Add a Property to an Array of Objects Using Array.prototype.map()

Susan Sarandon
Release: 2024-10-23 13:14:02
Original
929 people have browsed it

How to Add a Property to an Array of Objects Using Array.prototype.map()

Adding a Property to an Array of Objects

You have an array of objects, and you want to add an additional property named "Active" to each object. The expected output should have the property added to all the objects in the array.

To achieve this, you can use the Array.prototype.map() method. This method creates a new array by transforming each element in the original array. You can use it to add the "Active" property by mapping each object to a new object that includes the additional property.

Here's an example of how you can use Array.prototype.map() to add the "Active" property:

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

In the above code, the map() method creates a new array by iterating through each object in the Results array. For each object, it returns a new object that includes the original properties along with the added "Active" property set to "false".

The map() method is a powerful tool for transforming arrays of data. It allows you to easily modify the elements of an array without mutating the original array. For more information about the map() method, you can refer to the MDN documentation: 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 Property 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
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!