What is the best way to add up the attributes of objects within an array and save the total to the main

I have a collection of objects, illustrated here:

var obj = {
   "ABC" : {
      "name" : "ABC",
      "budget" : 0,
      "expense" : 0,
      "ledgers" : [{
        "Actual1920": 10,
       "Budget1920": 20,
      },
      {
       "Actual1920": 10,
       "Budget1920": 10,
      }]
  },
  "PQR" : {
    "name" : "PQR",
    "budget" : 0,
    "expense" : 0,
    "ledgers" : [{
      "Actual1920": 10,
      "Budget1920": 20,
    }]
  }
}

The task is to sum up the values under Actual1920 within the ABC object and its Ledgers array, then assign it to ABC's budget. The same process should be applied to compute the total for expense.

Desired Outcome

var obj = {
   "ABC" : {
      "name" : "ABC",
      "budget" : 30,
      "expense" : 20,
      "ledgers" : [{
        "Actual1920": 10,
       "Budget1920": 20,
      },
      {
       "Actual1920": 10,
       "Budget1920": 10,
      }]
  },
  "PQR" : {
    "name" : "PQR",
    "budget" : 20,
    "expense" : 10,
    "ledgers" : [{
      "Actual1920": 10,
      "Budget1920": 20,
    }]
  }
}

Add the totals from Actual1920 to expense and Budget1920 to budget accordingly.

Answer №1

To calculate the total of the desired field in a new array named ledgers, you can utilize the forEach() and .map() functions.

var arr =  [  {
    "name": "Salary",
    "budget": 0,
    "expense": 0,
    "remaining": 0,
    "ledgers": [
    {
    "Actual1920": 9009006,
    "Budget1920": 46861141.9709555,
    "CostOwner": "Lakshmi Mohan",
    "LTRevExp": "Expense-EB",
    "LedgerBudget": "Salary",
    "LedgereType": "Salary-Teaching",
    "RemainingAmount": 37852135.9709555,
    "leadgerLevel": "EBITDA",
    "quaterFour": 11715285.492738875,
    "quaterOne": 11715285.492738875,
    "quaterThree": 11715285.492738875,
    "quaterTwo": 11715285.492738875
    },
    {
    "Actual1920": 7765368,
    "Budget1920": 33788679.599044524,
    "CostOwner": "Lakshmi Mohan",
    "LTRevExp": "Expense-EB",
    "LedgerBudget": "Salary",
    "LedgereType": "Salary-Non Teaching",
    "RemainingAmount": 26023311.599044524,
    "leadgerLevel": "EBITDA",
    "quaterFour": 8447169.899761131,
    "quaterOne": 8447169.899761131,
    "quaterThree": 8447169.899761131,
    "quaterTwo": 8447169.899761131
    },
    {
    "Actual1920": 0,
    "Budget1920": 0,
    "CostOwner": "Lakshmi Mohan",
    "LTRevExp": "Expense-EB",
    "LedgerBudget": "Salary",
    "LedgereType": "Salary-Contract & Professional",
    "RemainingAmount": 0,
    "leadgerLevel": "EBITDA",
    "quaterFour": 0,
    "quaterOne": 0,
    "quaterThree": 0,
    "quaterTwo": 0
    }
    ]
    },
    {
    "name": "Scholarship & Discounts",
    "budget": 0,
    "expense": 0,
    "remaining": 0,
    "ledgers": [
    {
    "Actual1920": 1460000,
    "Budget1920": 15977747.5,
    "CostOwner": "Vineeta S",
    "LTRevExp": "Expense-EB",
    "LedgerBudget": "Scholarship & Discounts",
    "LedgereType": "Scholarship & Discount",
    "RemainingAmount": 14517747.5,
    "leadgerLevel": "EBITDA",
    "quaterFour": 0,
    "quaterOne": 3723000,
    "quaterThree": 12254747.5,
    "quaterTwo": 0
    }
    ]
    }
   ]

var ledger = {"salary" : 0 , "Expense" : 0 , "remaining" : 0};
arr.forEach(function(singleObject){
    singleObject.ledgers.forEach(function(singleArrObject){
        Object.keys(singleArrObject).map((o)=>{
            if(o == "Actual1920"){

                ledger.salary = ledger.salary + singleArrObject[o]; 
            }
            else if(o == "Budget1920"){
                ledger.Expense = ledger.Expense + singleArrObject[o];
            }
            else if(o == "RemainingAmount"){
                ledger.remaining = ledger.remaining + singleArrObject[o];
            }
        })
    })
});
console.log(ledger);

Answer №2

    arr.forEach(function(obj){
       console.log(obj);
       obj.ledgers.forEach(function(arrObj){
        Object.keys(arrObj).map((key)=>{
            if(key == "Actual1920"){
                obj.expense = obj.expense + arrObj[key]; 
            }
            else if(key == "Budget1920"){
                obj.budget = obj.budget + arrObj[key];
            }
            else if(key == "RemainingAmount"){
                obj.remaining = obj.remaining + arrObj[key];
            }
        })
    })
});

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

Passing the value in a td element to a JavaScript function using Thymeleaf onClick

Trying to utilize "Thymeleaf" for the first time, I am attempting to pass a value to JavaScript with the following code: onclick="getPropId('${properties.id}')" The corresponding function is as follows: getPropId(inputID){alert(inputId);} Unf ...

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

Toggle Visibility of Elements with Javascript and Html

I've been working on implementing a "Show All / Hide All" feature. Currently, clicking on the text opens the image and text individually. However, I am looking to add a functionality for expanding all divs at once. To see how it currently functions, ...

Attempting to minimize the repetition of code in Redux by implementing some utility functions

Is there a potential issue with the method I'm attempting in this URL: The concept involves altering only the actions file when introducing a new action. One improvement I am considering is recursively merging the status passed from the actions with ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

Just encountered an issue stating "PrismaClient cannot run in the browser" while working with [Next.js]

My initial plan was to log all the IDs of news in my database using console. However, when I executed the code, an error occurred as shown in this image. What is the best way to address and resolve this issue? https://i.stack.imgur.com/ci8G1.png ...

What is the best way to retrieve the final entry from a JSON file while using json server with Angular?

I'm currently working with a JSON file where I am making post requests followed by get requests. My goal is to retrieve the latest record in each get request after submitting a post request. For example: [ { "id": 1, "title&qu ...

Error: An anomaly token was encountered while deploying a Laravel/Vue project using the pipeline yml in Yarn Run

I have encountered a challenge while trying to deploy my project to a server using bitbucket-pipeline with a .yml script. The project consists of a Laravel backend with PHP 7.4 and a Vue Js frontend. The issue arises during the frontend build process with ...

Prevent financial disagreement by utilizing jQuery carefully

While I'm sure this question has been asked in a similar form before, my searches for the $ sign did not return any results here. I have already built a large system and heavily utilized jQuery, using $ as a reference. Now, I don't want to rever ...

The Recharts Line chart fails to display newly added data points when data is updated

My app features a straightforward tool that enables users to monitor their weight changes over time. Despite successfully receiving new data in the props, the chart does not update and display the new point. Recharts Component: import React from 'rea ...

Submitting a form in Rails without refreshing the page and dynamically updating the view

Hello everyone! I am currently utilizing Rails and in my process, I would like the user to perform the following steps on the same page: Input their address Completing the form Submit the form Clicking to submit Update the view to display the add ...

It appears there was a mistake with [object Object]

Hey there, I'm currently working with Angular 2 and trying to log a simple JSON object in the console. However, I keep encountering this issue https://i.stack.imgur.com/A5NWi.png UPDATE... Below is my error log for reference https://i.stack.imgur.c ...

Stop json_encode from converting empty strings to null values

Can the PHP function json_encode be configured to retain empty string values instead of converting them to null? UPDATE: After further investigation, it appears that the default behavior of the json_encode function already retains empty string values wi ...

Is there a way for me to convert a JBuilder view into a JSON string format?

I'm currently utilizing JBuilder to create JSON output on my project. The data is being generated by an index.json.jbuilder file, but I am facing a challenge when trying to convert it into a string format. Despite attempting methods like @my_object.to ...

Error: Node-Sass - Unable to download win32-x64-57_binding.node

Currently in the process of getting a retired colleague's program up and running, but when attempting to execute meteor run I encounter this error. While loading package materialize:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Encountering a ReferenceError message that says "readFile is not defined

Currently, I am in the process of learning Node.js and encountering an issue. When I type 'node .' in the terminal, I receive a ReferenceError: readFile is not defined message. Below is the code snippet: const express = require("express"); co ...

Close button for body

I have created a form that floats in the center of the screen On this form, I have included a button designed to close it However, I would like for the form to be closed anywhere on the screen when clicked with the mouse Here is my code: $(".offer-clo ...

In Vue, the sorting and filtering functionality is not always honored by JS-enhanced form components

Currently, I'm developing a simple to-do app using Vue. In this application, each item in a list generated by v-for consists of standard form fields like text inputs and checkboxes, as well as special form fields which are Vue components for WYSIWYG e ...

Using a JSON file as a database for a project featuring HTML, CSS, and Vanilla JavaScript

Our task was to create a project that exclusively utilized JSON files for data storage. The data structure we were working with resembles the following: [ { "aircraftName": "Boeing 747", "departDate": 1640173020000, ...

What is the best way to connect a custom JSON response, sourced from a QueryReadStore, to a dijit FilteringSelect component?

I am facing some challenges in getting custom formatted JSON data into a dijit.form.FilteringSelect. This issue might also apply to other types of dijit select boxes. Update: One thing I noticed when using a FilteringSelect instead of a ComboBox is that v ...