Make object calculations easy with the power of JavaScript

I've stored a JSON object in a variable and I'm performing calculations based on its properties. However, the current method of calculation seems lengthy, especially as the data grows larger.

I'm searching for a more concise approach to perform these calculations.

Below is the JSON data saved in a JavaScript file:

var obj = {
  "Open": [{
    "Sprint_2":null,
    "Sprint_3":null,
    "Sprint_4":null,
    "Sprint_5":6,
    "Sprint_6":38,
    "Sprint_7":7
  }],
  ...
};

Here's an example of a calculation I'm currently using to sum numbers from different keys:

var totDone = obj.Ready_for_Test[0].Sprint_2 + ... + obj.Accepted[0].Sprint_7;
console.log(totDone); 

If the JSON data expands, my calculation algorithm will become cumbersome. Is there a simpler way to handle these calculations efficiently?

Answer №1

To calculate the sum using the getSum function, follow these steps:

var result = getSum(dataObject, 'Test');
console.log(result);

function getSum(data, key){
    var sprints = data[key][0];
    var total = 0;
    for (var sprint in sprints){
         if(sprints[sprint]){
              total += sprints[sprint];
         }
    }
    return total;
}

To find the total of all values:

 var grandTotal = 0;
 for (var keyValue in dataObject){

      grandTotal += getSum(dataObject, keyValue);
 }

console.log(grandTotal);

If you want to add specific sprint values only, provide a list of those sprint names like this:

function getSum(data, key, listOfSprints){
    var sprints = data[key][0];
    var total = 0;
    listOfSprints.forEach(function(name){
        if(sprints[name]){
              total += sprints[name]
         }
    });
    return total;
}

getSum(dataObject, 'Design', ['Sprint_2', 'Sprint_3']);

Answer №2

If you're looking to calculate the total sum of non-null values in a JSON object, you can achieve this using nested for loops. Check out this straightforward solution below: https://jsfiddle.net/qr9bnw3m/1/

let totalSum = 0;
for (key in data) {
  for (subKey in data[key]) {
    for (item in data[key][subKey]) {
      if (data[key][subKey][item] !== null) {
        totalSum += data[key][subKey][item];
      }
    }
  }
}
console.log('Total sum of non-null values: ' + totalSum);

Answer №3

One crucial aspect is the organization of data structures. By melding suggestions from the comments section with personal experiences, a structured approach to data is recommended.

// Here lies your JavaScript Object
var backlog = {
    Open: [
        null, null, null,
        6, 38, 7
    ],
    Design: [
        null, null, null,
        null, 1, null
    ],
    Requirement: [
        null, null, null,
        1, 1, null
    ],
    Ready_for_Build: [
        null, null, null,
        4, 2, null
    ],
    Build: [
        null, null, null,
        12, 1, null
    ],
    Ready_for_Test: [
        null, null, null,
        4, 4, null
    ],
    Test: [
        null, null, null,
        5, 6, null
    ],
    Ready_for_Acceptance: [
        null, null, null,
        3, null, null
    ],
    Accepted: [
        38, 43, 57,
        19, null, null
    ],
    Total_Bugs: [
        47, 39, 71,
        39, null, null
    ],
    Bugs_Success: [
        37, 25, 42,
        11, null, null
    ],
    Bugs_In_Progress: [
        null, null, 7,
        4, null, null
    ]
};

A notable observation is the reduced use of syntactical characters ({, }, [, ], :, ', and "), showcasing a simplified code structure which can aid in streamlining subsequent coding tasks.

To calculate sums efficiently, functions such as Array.prototype.reduce() and Array.prototype.map() are instrumental for iterating over data sets and performing complex calculations with minimal redundancy.

// Collection of stages to sum up
var postDevBacklogStages = [
    backlog.Ready_for_Test,
    backlog.Test,
    backlog.Ready_for_Acceptance,
    backlog.Accepted
];

// Sum calculation function for arrays
var sumArray = function (array){
    return array.reduce(function(previousValue, currentValue, currentIndex, array){
    if (typeof(currentValue) != "number") {
        return previousValue;
    } else {
      return previousValue + currentValue;
    }
  });
};

// Calculate sums for each stage
var postDevBacklogStageSums = postDevBacklogStages.map(function(currentValue, index, array){
    return sumArray(currentValue);
});

// Find total sum of all stages
var sumTotal = sumArray(postDevBacklogStageSums);

console.log(postDevBacklogStageSums); // [8, 11, 3, 157]
console.log(sumTotal); // 179

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

Display thumbnail images in jquery-ui dropdown menu

Hello, I'm looking to display a small image (the user's thumbnail) on the jquery-ui dropdown by making an ajax call. As someone new to ajax and unfamiliar with jquery-ui, I would appreciate some guidance in the right direction. Thank you! HTML/J ...

The initial setting of [opened]="true" causes an issue with the Angular Material date range picker

Recently, we completed the upgrade of our app from Angular 14 to 15.2.9, which includes Angular Material. The migration process went smoothly, and now our app is compiling and running without any errors. However, we encountered an issue with the mat-date-r ...

I'm having trouble resolving the issue in my React App after attempting to export a functional component. How can I troubleshoot and

Since the first week of this online course on Coursera.org, I've been struggling to get my React app to display. Even after watching videos and revising the code multiple times based on Google search results, I couldn't make it work. Despite seek ...

The Steam marketplace displays all prices for Dota 2 items

I am attempting to retrieve a collection of pricing information for items in Dota 2 using the following code: <?$urll2 = "http://api.steamapis.com/market/items/570?api_key=******"; enter code here$urljson2 = file_get_contents("$urll2"); $ ...

An error message pops up when using Next.js with Sass, indicating that a suitable loader is required to handle this file type

I've been struggling to properly wire up my next.js project with SCSS, but no matter what I try, it just won't work. I double-checked my setup for compiling SCSS files, but the error message keeps popping up: /scss/style.scss 1:0 Module parse f ...

Jackson returns a null value when deserializing the java.utils.logging.Level class

I have been facing challenges while deserializing a complex bean using Jackson and Lombok builder. Although I was able to resolve serialization errors related to other custom types, I am encountering issues specifically with the deserialization of a Level ...

Modifying button styles in Angular UI Datepicker

In this plunk, there is an Angular UI Datepicker with a template. I'm trying to customize the colors of the "Today", "Clear", and "Close" buttons by editing the popup.html. However, even after changing the classes in the code, the datepicker still sho ...

Guide to using jQuery to input a multi-line text into a field

Dealing with a value that spans multiple lines obtained from PHP has been challenging due to the structure of textareas. The standard method of inserting it into the textarea is not feasible in this case. I resorted to using jQuery for this purpose, but ...

Reverting Changes Made with JQuery Append

I have a table where each cell contains a button. When the button is pressed, it adds text to the cell. I am looking for a way to remove this text from the cell when the same button is pressed again. It's important to note that this button appears mul ...

What steps can I take to address security issues related to iframes?

Are there other security risks to consider when using iframes besides XSS vulnerabilities? How can I ensure that my website is secure when utilizing iframes? I've seen some JavaScript code that uses top.window, but I'm hesitant to rely on client ...

Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule. I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule). Below is a snippet of app.componen ...

What's the best way to neatly display an array of objects with two values using JSON?

My JSON data is structured like this: "members": [ "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e2e7eeeaedc3f7e6f0f7ade0ecee">[email protected]</a>", "<a href="/cdn-cgi/l/email-pr ...

TypeCastException: MyViewHolder is incompatible with ProgressViewHolder

Attempting to integrate Endless Infinite Scrolling with RecyclerView, I am facing an issue where all records are being displayed at once without any progress while trying to scroll to the bottom. Below is my News_Adapter code: public class NewsAdapter ext ...

I am struggling to capture the user's input and display it on a webpage using HTML and JavaScript. Can you help me identify where I may be going wrong in this process?

Good day! I am fairly new to the programming world and have recently embarked on my first JavaScript project. I've chosen to create a simple budgeting app. However, I'm struggling with displaying user input on the page. Something seems off with ...

Error: The function `res.status` is unsupported

I've been working on a function to allow uploading images to imgur through my express API (nodejs), but I'm running into an issue when calling a function that returns a promise: TypeError: res.status is not a function at uploadpicture.then T ...

Guide to importing external CSS styles into Angular 2 using the require method

I'm facing an issue with loading an external css file in different environment files. My setup includes two environments: development and production. Loading the css file locally works fine in development mode, but not in production mode. environment ...

Troubleshooting React Native in VS Code using Node shims

I recently started working on a React Native project using the Ignite CLI 2.0.0 default boilerplate, and I find myself in need of some dependencies from node-based packages. To address this, I created files named transformers.js, babel-transform.js, and r ...

Customize Vue.js: Disable Attribute Quote Removal for Individual Pages

We have a requirement to turn off the minify.removeAttributeQuotes property for certain pages. This is the content of my vue.config.js: const packageJson = require('./package.json') module.exports = { assetsDir: packageJson.name + &apos ...

Encountering a JSON error message "Abstract type cannot be instantiated" while making a POST request to a Restful server

I am attempting to send a POST request to a Restful Server, using JSON format through Chrome's Advanced Rest Api add-on. Below is the JSON data: (with headers: Accept: application/json; Authorization: Basic....) { "datecreated": 1355237359326, "datem ...

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...