Is there a way for me to consolidate the properties of a complex nested object into the top level of an array of objects through either moving or summing them up?

I have a collection array that looks like this:

const collection = [
    {
      "name": "Top1",
      "data": [
        {
          "name": "shahnshah",
          "data": [
            {
              "name": "test1",
              "values": {
                "val1": 876,
                "val2": 3456
              }
            }
          ]
        },
        {
          "name": "Alex",
          "data": [
            {
              "name": "test1",
              "values": {
                "val1": 654,
                "val2": 300
              }
            },
            {
              "name": "test2",
              "values": {
                "val1": 676,
                "val2": 888
              }
            }
          ]
        }
      ]
    },
    {
      "name": "Top2",
      "data": [
        {
          "name": "shahnshah",
          "data": [
            {
              "name": "test1",
              "values": {
                "val1": 111,
                "val2": 300
              }
            }
          ]
        },
        {
          "name": "Alex",
          "data": [
            {
              "name": "test1",
              "values": {
                "val1": 100,
                "val2": 150
              }
            },
            {
              "name": "test2",
              "values": {
                "val1": 600,
                "val2": 50
              }
            }
          ]
        }
      ]
    }
  ];

I want to transform this data so I can display it in a table format with the total values for keys "val1" and "val2" added at the top level under their corresponding key (e.g. name). The expected end result should look like this.

[
    {
        "name": "Top1",
        
        // Only these two values will be extra
        "val1": 2206, // sum of 876 + 654 + 676
        "val2": 4644, // sum of 3456 + 300 + 888

        "data": [
          {
            "name": "shahnshah",
            "data": [
              {
                "name": "test1",
                "values": {
                  "val1": 876,
                  "val2": 3456
                }
              }
            ]
          }
        ]
    },
    {
     // next object continued here
    }
  ]

This approach allows me to show the sum of values at the top and eventually present it in a nested table.

Answer №1

const dataSet = [
    {
      "name": "Top1",
      "data": [
        {
          "name": "shahnshah",
          "data": [
            {
              "name": "test1",
              "values": {
                "val1": 876,
                "val2": 3456
              }
            }
          ]
        },
        {
          "name": "Alex",
          "data": [
            {
              "name": "test1",
              "values": {
                "val1": 654,
                "val2": 300
              }
            },
            {
              "name": "test2",
              "values": {
                "val1": 676,
                "val2": 888
              }
            }
          ]
        }
      ]
    },
    {
      "name": "Top2",
      "data": [
        {
          "name": "shahnshah",
          "data": [
            {
              "name": "test1",
              "values": {
                "val1": 111,
                "val2": 300
              }
            }
          ]
        },
        {
          "name": "Alex",
          "data": [
            {
              "name": "test1",
              "values": {
                "val1": 100,
                "val2": 150
              }
            },
            {
              "name": "test2",
              "values": {
                "val1": 600,
                "val2": 50
              }
            }
          ]
        }
      ]
    }
  ];

let transformedSet=dataSet.reduce((acc,current)=>{
 
 
current.val1=current.data.reduce((acc1,curr1)=>{  return acc1+curr1.data.reduce((a,c)=> a+c.values.val1,0);},0)
current.val2=current.data.reduce((acc1,curr1)=>{  return acc1+curr1.data.reduce((a,c)=> a+c.values.val2,0);},0)
 

acc=[...acc,current];
return acc;
},[])

 
console.log(transformedSet);
 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Searching for files in directories and subdirectories using Node.js

Although I found this solution, it seems to be quite slow. I am looking for the quickest way to traverse directories without using npm packages. Any suggestions? ...

Is there a way to automatically extend my content to fill the space on the page below the Material UI AppBar?

I am currently using React and Material UI React to develop my application. My goal is to implement the AppBar component with content underneath, without causing the entire page to scroll. I want the content to occupy the maximum remaining height and the f ...

Comparing Objects in an Array to Eliminate Duplicates and Make Updates in Javascript

I am working with an array of objects that is structured like this: 0: Object ConsolidatedItem_catalogId: "080808" ConsolidatedItem_catalogItem: "undefined" ConsolidatedItem_cost: "0" ConsolidatedItem_description: "Test Catalog Item" ConsolidatedItem_ima ...

Troubleshooting Problem with HTTP Requests in Angular 2 on Firefox Browser

I have encountered a peculiar issue with my Angular 2 application specifically on Firefox and all iOS browsers (Firefox, Safari). Whenever a user navigates to the /reports route in my application, I am making a REST API call using the ngOnInit method to f ...

The issue of a property name not existing on a type in Typescript and Angular2

The answer provided for this particular question using the find method is not functioning in TypeScript, resulting in a compilation error. After reviewing similar inquiries, it appears that each one has its own unique context. Below is the array being ref ...

Ways to identify when a React child element is overflowing

tl;dr How can I create a component that hides overflow and toggles views with a button? For example, the user can initially see tabs 1, 2, and 3 while tabs 4, 5, and 6 are hidden. Clicking a button will hide tabs 1, 2, and 3, and show tabs 4, 5, and 6 with ...

Tips for retrieving the current logged user's username using local storage in Angular Typescript

In my Angular application, users can log in with their email and password. I want to display the user's name in the dashboard menu as "Welcome James" when the current user is logged in. This information should be retrieved from localStorage and all us ...

Using Golang to encode JSON for parsing in JavaScript

I am working with a struct that looks like this: type User struct { Login string `json:",string"` PasswordNonce Nonce `json:",string"` PasswordHash HashValue `json:",string"` CreatedOn time.Time `json:",string"` Email ...

Exploring Angular Component Communication: Deciphering between @Input, @Output, and SharedService. How to Choose?

https://i.stack.imgur.com/9b3zf.pngScenario: When a node on the tree is clicked, the data contained in that node is displayed on the right. In my situation, the node represents a folder and the data consists of the devices within that folder. The node com ...

A guide on organizing an array and retrieving the index in hive

In my programming project, I need to arrange an array in descending order and also get the index array for reference. Here is an example of the data table I am working with: id | value_array 1 | {30, 40, 10, 20} 2 | {10, 30, 40, 20} My desired o ...

Managing additional components in request JSON when communicating with DialogFlow, previously known as Api.ai

My current challenge involves enhancing the information sent in a JSON request from my application to DialogFlow. While I am familiar with triggering events to send data calling an intent through the method described in Sending Parameters in a Query Reques ...

Get a compressed folder from jszip containing a PDF file that is either empty or blank

I'm facing a challenge with my Vue app where I need to compress a group of PDF files in a folder using JSZip. While testing with just one file, the zip downloads successfully but when I try to open the PDF file inside it, the content appears blank. I ...

Encountering an issue with the nativescript-carousel due to tns-platform-declarations

While constructing a nativescript carousel using the nativescript-carousel plug-in, I encountered an issue when running tns build android. The error message reads as follows: node_modules/nativescript-carousel/index.d.ts(1,22): error TS6053: File 'D: ...

Observing Arrow Keys as '0' during keypress event execution

When using Firebug for debugging in Firefox version 8.0.1, I set up a keypress event handler on an editable div. While every key press is successfully displayed in the console, I am encountering an issue with the arrow keys - the value of e.which in the co ...

Obtain the value of an element from a React UI Material component (e.g. ListItemText)

Incorporated an onClick() event where a function is invoked to retrieve and display the value of any clicked element within the HTML body in a web component. <div id="root" onclick="handleClick(event)"></div> This snippet o ...

Where should uploaded files be stored using ng-flow?

Initially, I am utilizing the ng-flow, which is an html5 file upload extension built on the angular.js framework. After uploading my files and logging the event in the console, I'm uncertain about where and how to store them. Below is my HTML code w ...

Steps for displaying the search results in a pop-up box

I'm having trouble figuring out what to put in the '()' of my JavaScript popup function. Can anyone help me with this issue? Thank you! :) <script> // Example of JavaScript popup window function function customPopup(url) { popupWindow ...

"Implementing usort to efficiently sort multiple fields with a mix of boolean

Here is the main array structure: Array ( [0] => Array ( [active] => true [age] => 15 ) [1] => Array ( [active] => false [age] => 10 ) [3] => Array ( [active] => false ...

An elusive static image file goes unseen within the realm of node.js/express

I am encountering an issue with serving static files in Express on Node.js. When I request a .css file from the server, everything works fine. However, if I try to load an image such as a jpg or png, it just shows a blank white page without any error messa ...

To visit a member's homepage, simply click on the image in the array with the help of PHP

Currently working on the development of a social networking platform, I have encountered an issue with the pagination page that displays search results for members. Here is an example of a search page: My goal is to allow users to click on a picture and b ...