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

Determining if a specific time falls within a certain range in JavaScript

I'm currently working on a Node.js application, but I have limited experience with Javascript. As part of my application, I need to implement validations for events and ensure that no two events can run simultaneously. To achieve this, I have set up ...

I am looking to modify the highlighted table cell whenever the value within it changes

I am currently working on a small project related to the Stock Market. In this project, I need to dynamically change the style of the td element based on data fluctuations - green highlight for an increase and red highlight for a decrease. In the provid ...

Select two main values from a group of Python dictionaries and create a new list, tuple, array, or dictionary where each position holds two main values from the first dictionary in the group

I am working with a list of dictionaries stored in a JSON file. After iterating through the list and each dictionary, I am extracting two specific key-value pairs from each dictionary element. For example, List[dictionary{i(key_x:value_x, key_y:value_y)}] ...

Uniform Height for Several Selectors

I came across a script on Codepen created by RogerHN and decided to customize it for a project I'm currently working on: https://codepen.io/RogerHN/pen/YNrpVa The modification I made involved changing the selector: var matchHeight = function ...

How can I retrieve JSON data from within a function and show it on a textfield in Swift programming language?

I've been exploring how to parse JSON data into Swift, specifically attempting to display the area of my pincode in a text field. In order to do this, I've created three Swift files: mapview.swift, maphandler.swift, and mapmodel.swift. The issue ...

Ways to stop Bootstrap 4 dropdown from appearing when clicking on an input field?

Here is a straightforward bootstrap dropdown menu example, but with a twist - the toggle element is a text input. Instead of showing the dropdown on click event, I want it to appear when the user inputs something so I can dynamically populate the menu base ...

Retrieving specific elements from an array and transferring them to a new array

As a beginner in the world of programming, I hope you don't mind me asking what may seem like a "noobish" question. I have recently come across an array that contains various values representing frequencies of occurrences - for example: {4, 5, 2, 7, 8 ...

Encountering an error with my electron application built using create-react-app

While I'm working on my project, my electron window is showing this error message. TypeError: fs.existsSync is not a function getElectronPath ../node_modules/electron/index.js:7 4 | var pathFile = path.join(__dirname, 'path.txt') 5 | ...

The Python interpreter behaves consistently across different platforms, except for a specific issue with json_set in Visual Studio Code

I can't seem to understand what's going on. The code works fine everywhere except in Visual Studio Code. Take a look at this example: import sqlite3 _connection = sqlite3.connect(":memory:") connection.row_factory = sqlite3.Row create_table = ...

Setting up various connections is made possible through Node.js Socket.io

In the process of developing a straightforward chat application using socket.io and incorporating passport.js for user authentication, an issue arises when users log out and then back in. The previous socket connection remains active, resulting in two conn ...

Merge the JSON data with the Node.js/Express.js response

Whenever I input somedomain.com/some_api_url?_var1=1 in a browser, the response that I receive is {"1":"descriptive string"}. In this JSON response, the index 1 can vary from 1 to n, and the "descriptive string" summarizes what the index represents. I am ...

Enable the expansion of a div by dragging and dropping an image onto it

Take a look at this fiddle. In this fiddle, I am able to drag and drop images onto the .drop-zone. However, I would like to enhance it so that when I drag an image onto it, the .drop-zone div expands to where I place the image. It's okay if the expand ...

Opting for PHP over JSON for the instant search script output

Is there a way to modify my Google Instant style search script, written in jQuery, to retrieve results from a PHP script and output PHP-generated HTML instead of JSON? Below is the current code: $(document).ready(function(){ $("#search").keyup(functi ...

Looking to spice up your static HTML site? Dive into the world of Ruby on

I recently developed an app that features a static HTML webpage containing text and images, and now I'm interested in incorporating Ruby on Rails to explore its capabilities further. After creating a basic RoR application, I copied the HTML content f ...

The ngClass directive does not seem to be functioning properly when utilizing multiple conditions

Trying to apply [ngClass] under different conditions. Here is what I have: condition [ngClass]="{'validator':lang.VideoURL!=null, 'labeltitle': lang.VideoURL==null}" However, when the value of lang.VideoURL is null, the labeltitle cl ...

Quickly view products in Opencart will automatically close after adding them to the cart and redirecting the

I've integrated the product quickview feature into my OpenCart theme, which opens a product in a popup. However, when I add a product to the cart from the popup, it doesn't update on the main page until I refresh. I'm looking for a way to re ...

implementing a smooth transition effect for image changes upon hover

I've been working on a React project where I created a card that changes its image when hovered over. I wanted to add a smoother transition effect to the image change using transition: opacity 0.25s ease-in-out;, but it doesn't seem to be working ...

What is the syntax for using escape characters in Vue?

Looking to create a website similar to CodePen? I have developed a library of assets including buttons, cards, and effects, all built using vue.js. Each asset includes HTML, CSS, and sometimes JS code. In my vanilla JS version, I formatted the code using e ...

Tips on effectively managing an XMLhttp request to a PHP controller

Encountering an internal server error and nothing is being logged in the PHP error log. This issue persists despite not using any frameworks. DEV - controllers |-> user -> check_email.php - public_html |-> routes ...

Error occurred while attempting to execute the method

Here's a MongoDB Mongoose query we're dealing with: sampleSchema.find({ $where: "expired <= " + (new Date()) }) .limit(9) // Problems may arise from here .sort({ postedDate: -1 }) .then((docs) => { console.log(&apos ...