Home > Web Front-end > JS Tutorial > How to Aggregate Values for Similar Keys in an Array of JavaScript Objects?

How to Aggregate Values for Similar Keys in an Array of JavaScript Objects?

Susan Sarandon
Release: 2024-11-24 19:23:20
Original
1016 people have browsed it

How to Aggregate Values for Similar Keys in an Array of JavaScript Objects?

Aggregate Values for Similar Keys in an Array of Objects

Given an array of objects, where each object possesses a key named "name" and a corresponding value, the task is to group objects by their "name" and accumulate their "value" properties. For instance, if we had the following array:

[
    { 'name': 'P1', 'value': 150 },
    { 'name': 'P1', 'value': 150 },
    { 'name': 'P2', 'value': 200 },
    { 'name': 'P3', 'value': 450 }
]
Copy after login

The desired output would be:

[
    { 'name': 'P1', 'value': 300 },
    { 'name': 'P2', 'value': 200 },
    { 'name': 'P3', 'value': 450 }
]
Copy after login

To achieve this aggregation, we can adopt an iterative approach as follows:

  1. Create an Object to Hold Name-Value Pairs: Begin by creating an empty object. This object will be used to store the name-value pairs for the objects.
  2. Iterate through the Array and Accumulate Values: Iterate through the array of objects using forEach. For each object, check if the object's "name" property exists in the holding object as a property. If it exists, add the object's "value" property to the existing value. If it does not exist, set the value for the "name" property to the object's "value" property.
  3. Create a New Array with Aggregated Objects: Once all values have been accumulated in the holding object, create a new array. Iterate through the properties of the holding object and push new objects with "name" and "value" properties into the array.

This iterative approach ensures that objects with the same "name" are grouped together and their "value" properties are accumulated accordingly.

The above is the detailed content of How to Aggregate Values for Similar Keys in an Array of JavaScript Objects?. 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