Iterate over a JSON object to calculate the total sum of values based on distinct nested properties

Here is a JSON object that contains cost and author information. I am working on this in Express.js and using Underscore.

[
        {
            "Cost": 250,
            "author": { "id": "2", "name": "Joe", "workId": "5" }
        },
        {
            "Cost": 450,
            "author": { "id": "2", "name": "Joe", "workId": "6" }
        },
        {
            "Cost": 150,
            "author": { "id": "3", "name": "Tam", "workId": "7" }
        },
        {
            "Cost": 250,
            "author": { "id": "2", "name": "Joe", "workId": "8" }
        },
        {
            "Cost": 350,
            "author": { "id": "3", "name": "Tam", "workId": "9" }
        }
    ]
    

The desired output is:

Joe 950
Tam 500

I attempted to achieve this with the following code:

var iw={};
iw = Object.keys(myJsonObject.reduce((iw, curr) => {
    iw[curr.author.id].cost += parseInt(curr.cost);
    return iw;
}, iw)).map(key => iw[key]);
console.log("New ::"+iw);

However, I encountered an error:

TypeError: Cannot read property 'cost' of undefined
    at Object.keys.myJsonObject.reduce (repl:3:7)
    at Array.reduce (<anonymous>)
New ::[object Object]

Answer №1

according to Fraser

the issue in your original code was not checking if the user already exists in the iw object

here is the revised solution:

myJsonObject = 
[
    {   
        "Cost":250,
        "author": { id :"2", name : "Joe" , workId: "5" }
    },
    {   
        "Cost":450,
        "author": { id :"2", name : "Joe" , workId: "6" }
    },
    {   
        "Cost":150,
        "author": { id :"3", name : "Tam" , workId: "7" }
    },
    {   
        "Cost":250,
        "author": { id :"2", name : "Joe" , workId: "8" }
    },
    {   
        "Cost":350,
        "author": { id :"3", name : "Tam" , workId: "9" }
    }
]

var iw={};
iw = myJsonObject.reduce((iw, curr) => {
iw[curr.author.name] ? iw[curr.author.name] += curr.Cost : iw[curr.author.name] = curr.Cost;
    return iw;
}, iw);

console.log(iw);

Output:

{Joe: 950, Tam: 500}

Answer №2

There are various methods to achieve this, but a straightforward approach would be to utilize a forEach loop. The desired outcome is an object that stores the results.

const data = [
    {   
        "Cost":250,
        "author": { id :"2", name : "Joe" , workId: "5" }
    },
    {   
        "Cost":450,
        "author": { id :"2", name : "Joe" , workId: "6" }
    },
    {   
        "Cost":150,
        "author": { id :"3", name : "Tam" , workId: "7" }
    },
    {   
        "Cost":250,
        "author": { id :"2", name : "Joe" , workId: "8" }
    },
    {   
        "Cost":350,
        "author": { id :"3", name : "Tam" , workId: "9" }
    }
]

let authorTotals = {};

data.forEach(entry => authorTotals[entry.author.name] ? authorTotals[entry.author.name] += entry.Cost : authorTotals[entry.author.name] = entry.Cost);

console.log(authorTotals);

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

Configuring Tailwind CSS with PostCSS in a Nuxt project

Error Message "In order to avoid issues with features like alias resolving inside your CSS, please make sure to use build.postcss in your nuxt.config.js file instead of an external configuration file. Support for external config files will be depreca ...

Having trouble retrieving textfield value with jQuery

On my website, I have an invoice.jsp page that requires jQuery to calculate values in textboxes. Within the invoice, there is a quantity textbox. When a user enters a quantity, the price should be dynamically calculated as (total_subPrice= unit_price * qu ...

The guarantee is that it does not wish to proceed to the next stage if the form fails to submit on two occasions

Currently, I am developing a login page in Node.js using Express.js with a Neo4j database. In order to determine if a user already exists in my database, I have created a Models (MVC) structure named Users. Within this structure, there is a Class declared ...

Is there more to AJAX than just fetching a JSON file?

I am in need of using AJAX to achieve my goal. My aim is to have the content of specific subpages displayed in the HTML markup below when a particular link in a list is clicked. This data can be readily accessed from the database via the CMS's API (I ...

Encountering a Type Error while attempting to display items from an array

Encountering an issue while attempting to load quiz questions from a db.json server. The error message reads: "TypeError: this.state.questions[this.state.currentQuestion] is undefined". In order to provide more context, here's a link to a sandbox of m ...

HTML5Up! Skyrocketing with Meteor showers

While attempting to utilize a responsive site template from , I encountered several issues. To test the template, I downloaded the Striped package and created a clients folder in a Meteorite app where I placed the Striped folder. In order to make it work, ...

What is the best way to trigger a method once an image has completed loading and rendering?

Is there a way to trigger a method once an image has finished loading and displaying on the web browser? Here's a quick example using a large image: http://jsfiddle.net/2cLm4epv/ <img width="500px" src="http://www.digivill.net/~binary/wall-cover ...

Automatically update a separate page upon adding new data in Laravel 5.8 using Ajax

I have been exploring different methods on how to automatically update another page or blade file when data is changed. Specifically, I want the data in my wintwo.blade.php to be refreshed whenever I click the Call Next button on my call.blade.php. User i ...

Display Image Automatically Upon Page Opening

Currently, I have an HTML file that includes the following code: <img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid"> I am attempting to retrieve the image from a file when the webpage loads using the server.js file ...

Updating an API parameter in React's setState doesn't reflect the new changes

Having trouble with a web app that I'm currently developing. The issue arises on the recipe page where the search functionality isn't updating as expected. Although it is binded to the Enter key and the request itself works, the state update do ...

Leverage JavaScript to run a snippet of PHP code directly (without utilizing a separate PHP file)

I am looking for a way to integrate PHP into my web page using JavaScript and AJAX. I want the PHP file to be included and executed as if it is part of the native page, allowing me to utilize features like GET requests. <div id="firstAjaxDiv">Defaul ...

Creating a sleek navigation bar and sliding feature within the header of your Ionic 2

I am looking to create a sliding header for my website where the gallery hides and the navbar moves to the top as I scroll down, similar to the gif provided. Any help or ideas on how to achieve this would be greatly appreciated. Thank you. https://i.sstat ...

Is there a way to organize a specific column based on user selection from a drop down menu on the client side?

When selecting Timestamp from the drop-down menu, I expect the TimeStamp to be sorted in either ascending or descending order. Similarly, if I choose Host, the Host should be sorted accordingly. Despite using the Tablesorter plugin, sorting doesn't s ...

Exploring Node.js: Managing Memory Consumption for Efficiency

I'm currently setting up multiple Node applications on one server, and I'm particularly worried about memory usage. Is there a specific amount of physical memory needed for a basic Node.js express service to run? Also, is there a method to limit ...

URL-based authentication using Passport.js

I am currently working on my app using Express JS and Passport JS. My goal is to allow a new user to automatically log in once by accessing a specific URL. I have the ability to retrieve the user information from the database based on the URL provided, re ...

What is the best way to transform a JSON array in text format into a JSON object array using NodeJS or JavaScript?

I have a RESTful API built with Node.JS and ExpressJS. I want to retrieve a JSON array from the FrontEnd and pass it into my API. api.post('/save_pg13_app_list', function (req, res) { var app_list = { list_object: req.body.li ...

using ng-class or ng-style for displaying error messages when validating a text area content

I'm curious about the most effective "angular" method for changing the character count style for validation purposes. I have a text area with a 250-character limit. Instead of restricting users to exactly 250 characters, we want to allow them to excee ...

Accessing the raw body of a POST request in Node.js

In my tradingview platform, I have set up an alert that sends a webhook request to my server with plain text information. The issue is that the webhook only sends plain text and not JSON data. Is there a way to retrieve this plain text data from the webho ...

Positioning CSS for a Responsive Button

Currently, I am working on making my modal responsive. However, I am encountering an issue with the positioning of the "SAVE" button. The button is not staying in the desired position but instead disappears. Below is the snippet of my HTML and CSS: .dele ...

What is the best way to include multiple views in a main HTML template in Angular?

Is there a way to load two HTML files into a base HTML file? Essentially, I have a base HTML file with a header and content view, and I want to load different HTML files into each of them. Here is the base HTML file structure: <div class="container"> ...