combining different sets of data within a JSON object

Is there a way to calculate the total sum of values in a JSON dataset?

I'm attempting to add up all the values in my dataset under the field TaxAmount:

const url = "https://...........";
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        const data = JSON.parse(xhr.response);
        console.log(data);           

    }
};
xhr.open("GET", url, true);
xhr.send();

Here is a peek at the data:

https://i.sstatic.net/ZqXie.png

If we examine one of the objects in the array returned above:

{
   [functions]: ,
   __proto__: { },
   AccountID: null,
   AccountUID: null,
   AgentCost: 0,
   Amount: 24.3,
   AccountsItemID: null,
   TaxAmount: 2.01
}

I've made an effort to total the TaxAmount for all elements as follows:

let totalTaxAmount = data.reduce(function(previousValue, currentValue) {             
         return previousValue += currentValue["TaxAmount"];
    }, 0);

Do you think using a data.forEach.reduce would be more appropriate?

Is there a way to calculate the total sum of values in a JSON dataset?

Answer №1

Here is a helpful snippet to calculate the total tax amount:

var transactions = [
{
   AccountID: null,
   AccountUID: null,
   AgentCost: 0,
   Amount: 24.3,
   AccountsItemID: null,
   TaxAmount: 2.01
},
{
   AccountID: null,
   AccountUID: null,
   AgentCost: 0,
   Amount: 24.3,
   AccountsItemID: null,
   TaxAmount: 3.01
}
];

 var totalTaxAmount = transactions.reduce(function(previousValue, currentValue) {             
         previousValue += currentValue["TaxAmount"];
         return previousValue;
    }, 0);
console.log(totalTaxAmount);

Answer №2

It is recommended that you calculate the sum of pv and cv, with the second argument for reduce set to 0 instead of an object:

var totalTaxAmount = data.reduce(
  function(pv, cv) {
    /** Added a return statement and kept pv unchanged */return pv + cv["TaxAmount"];
  }, 
  /** Updated to zero */0
);

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

AngularJS controller failing to update the angular variable

Currently diving into the world of angularjs, so any guidance would be greatly appreciated! I have been working on a basic angular application that compares two password strings in ng-controller and provides a brief message indicating if they match or not. ...

Unable to fetch local file using ajax from a local HTML page

According to Same Origin Policy, the SOP should not be applied to the file:// protocol. However, I'm having trouble with my code. I am running a testing page from my local system, and both when I try to access abc.txt in the same directory as the HTML ...

Encountering an Unresolved Runtime Issue: TypeError arises when attempting to access properties of undefined (specifically 'call') while utilizing the Image component in next.js

I'm currently experimenting with the Image component offered by next.js. This Is My Basic Header Component import Image from 'next/image' import React from 'react' import myImage from '../assets/IMG-20221115-WA0001.jpg' ...

The input field will remain inactive until the radio button is selected (HTML)

I am trying to create a form with two fields - one text input and one select tag. I want only one of these fields to be enabled at a time, depending on which radio button the user clicks. If the user selects the first radio button, the input field should ...

Using Gmail in conjunction with Heroku for email delivery

After completing an order in my web app, I want to automatically send a confirmation email. I decided to use Nodemailer as it is a popular npm package for this purpose. I successfully coded the functionality and tested it in my local environment. Howeve ...

Creating a multi-dimensional array using information from a database

I have a unique challenge where I am utilizing a template that generates a menu with a specific structure. In my database, I have various menus stored and I've successfully retrieved them. However, the issue arises when I need to figure out a way to d ...

Unable to insert an array within a function

I've searched for the answer but couldn't find it - my array is not pushing to datahasil. How can I push the array hasil into datahasil...?? const data1 = await JadwalBooking.aggregate([{ $project: { "keterangan": "$keterangan", ...

Utilize the jQuery function as a callback argument

There is a jQuery plugin that I am currently working on: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title></title> <script type="text/javascript" sr ...

Designing a personalized user template for a feature in Angular 2

My component currently has a default template: import {Component} from 'angular2/core'; @Component({ selector: 'my-component', template: ` <div class="container"> ...

Extract only the contact information stored within a complex JSON structure

I am faced with a challenge of extracting specific data, particularly the phone number, from a deeply nested JSON structure using the Newtonsoft dll library. The JSON request I'm dealing with has a structure similar to this: [{ "name": "sam", ...

Ember-Data: Extracting nested JSON properties with ease

Upon receiving JSON data, it is presented in the following format: { "status": "success", "data": { "debtor": { "debtor_id": 1301, "key": value, "key": value, "key": value } } } The challenge lies in configuring the ...

Exploring the elements within array structures

I'm facing an issue with my API response. I'm trying to filter the links and check if the source and target name properties in each object match a specific string. However, I am having trouble accessing the name property. Any suggestions on how I ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

Transform JSONB arrays from Postgres into a JavaScript array containing individual JSON elements

Having some challenges with postgresql(9.4) and javascript. I'm attempting to convert a jsonb[] datatype into an array/list of JSON values in javascript, containing only one element(json) for simplicity. var s = { "player": "{\"{\\&bso ...

The JSON data failed to translate the integer field

My objective is to parse a JSON file. Although the current code successfully parses the file, it encounters an issue with the id field values, which are all showing as 0. This issue persists despite the fact that the JSON file contains specific id values f ...

Cycle2 does not display the cycle pager

I am currently working on creating a slideshow for a website where the images slide automatically (which is functioning properly). I want to include round buttons below the slideshow for navigation, but unfortunately, the buttons are not showing up despite ...

Material-UI Autocomplete can only save and display one specific property of an object at a time

Can someone help me with implementing Autocomplete from Material-UI? I want to store only a specific property value and not the entire object. For example, let's say I want to store the property Value, but it could be any other property as well. con ...

In JavaScript, there is a missing piece of logic when iterating through an array to find

I am working on a solution to populate empty values when data is not available for specific months. You can view my progress on Plunker here: http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview $scope.year = [ {"month":"mar", "val":"23"}, {"month":"feb", ...

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

What is Flask's approach to managing JSON data?

I am currently developing an editable table using FLASK, JSON, and jQuery. After serializing the form, I send it via $.getJSON, as shown at the bottom of my JS code: This is the JS code: $(function(){ $('tbody').on('click', &apos ...