Using JavaScript to reduce, group, and sum nested objects

I'm a third-year student working on my first internship project and struggling with organizing and aggregating data from a JSON object. The goal is to group the data by name, calculate total weight per name, and sum up the grades for each entry. I've been attempting this task for the past two days without much success. The desired output should be in the format of {name, weightTotal, grade{grade1total:, grade2total, grade2total}}. I've researched numerous Stack Overflow questions and experimented with reduce and foreach functions, but I can't seem to grasp the concepts. This information is crucial for me to proceed with the frontend development and display the results in a table. Just to provide some context, this data is retrieved from a REST endpoint.

Data

"data": [
    {
      name: "france Naicin",
      avgTotalWeight: 16,
      grade: {
        grade1: 16,
        grade2: 0,
        grade3: 0,
      },
    },
    // Additional data entries...
  ],

Current Code:

let aggregatedData = [];

    for (let i = 0; i <= data.length; i++) {
      if (!data[i]) {
        continue;
      }

      const {avgTotalWeight} = data[i];
      const {name} = data[i].truerun.batch.shellfish;
      const {alias} = data[i].truerun.grade_list;

      // Logic for calculating grades based on alias...

      let entry = {
          name: name,
          avgTotalWeight: avgTotalWeight,
          grade: {
            grade1: grade1,
            grade2: grade2,
            grade3: grade3,
          },
        };

        aggregatedData.push(entry);
      }
    }

    return aggregatedData;

Answer №1

To achieve the desired outcome, you can utilize the reduce method.

If there is a situation where the `grade` key may increase dynamically, you can modify the code to accommodate infinite keys within the `grade` object by replacing:

isExist.grade.grade1 += grade.grade1;
isExist.grade.grade2 += grade.grade2;
isExist.grade.grade3 += grade.grade3;

with:

Object.keys(isExist.grade).forEach((key) => {
  isExist.grade[key] += curr.grade[key];
});

const obj = {
  data: [
    {
      name: "france Naicin",
      avgTotalWeight: 16,
      grade: {
        grade1: 16,
        grade2: 0,
        grade3: 0,
      },
    },
    {
      name: "pacific gigas",
      avgTotalWeight: 16,
      grade: {
        grade1: 16,
        grade2: 0,
        grade3: 0,
      },
    },
    {
      name: "france Naicin",
      avgTotalWeight: 13,
      grade: {
        grade1: 13,
        grade2: 0,
        grade3: 0,
      },
    },
    {
      name: "france Naicin",
      avgTotalWeight: 14,
      grade: {
        grade1: 14,
        grade2: 0,
        grade3: 0,
      },
    },
    {
      name: "france Naicin",
      avgTotalWeight: 15,
      grade: {
        grade1: 15,
        grade2: 0,
        grade3: 0,
      },
    },
  ],
};

const result = obj.data.reduce((acc, curr) => {
  const { name, avgTotalWeight, grade } = curr;
  const isExist = acc.find((o) => o.name === name);
  if (isExist) {
    isExist.weightTotal += avgTotalWeight;
    isExist.grade.grade1 += grade.grade1;
    isExist.grade.grade2 += grade.grade2;
    isExist.grade.grade3 += grade.grade3;
  } else {
    acc.push({
      name,
      weightTotal: avgTotalWeight,
      grade,
    });
  }
  return acc;
}, []);

console.log(result);

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

Express server continuously returning 404 error for all requests originating from the index page

Experiencing a challenge with the express/gulpfile.js code. Express can serve the index.html without issue, but it fails to navigate to the lib/* directory resulting in all requests for resources at the top of my index.html returning 404 errors. Browser-s ...

Switching the body's background image dynamically using javascript

I'm attempting to switch up the background image using JavaScript. Here's how I've defined the background: body { background: black; overflow-x: hidden; overflow-y: hidden; } body:before { overflow-x: hidden; overflow ...

Removing an element from an array within MongoDB

After closely examining my mongodb data structure, it appears like this: [ { "_id": "582bc918e3ff1bf021ae8b66", "boardName": "Test Board", "created_at": 1479264483957, "__v": 0, "person": [ { "name": "Steve", "w ...

How to pass GetServerSideProps into Page component props in Next.js with custom _app.js

Having issues integrating GetServerSideProps into my Next.js app. Despite the network call successfully fetching data and generating the pageName.json, the response data is not being injected into the page props as expected. Below is a snippet of my page ...

Improving the efficiency of JSON web services through Retrofit optimization

Currently, I am using Retrofit and have implemented the ItemTypeAdapterFactory class which implements TypeAdapterFactory and handles the read method. Everything is functioning perfectly, but I have noticed a significant slowdown when dealing with a large a ...

Module Ionic not found

When I attempt to run the command "ionic info", an error is displayed: [ERROR] Error loading @ionic/react package.json: Error: Cannot find module '@ionic/react/package' Below is the output of my ionic info: C:\Users\MyPC>ionic i ...

Using Json.Net: Learning to Exclude Null Elements When Deserializing Array JSON Data

My JSON data looks like this: { "Variable1": "1", "Variable2": "50000", "ArrayObject": [null] } In my code, I have the following stubs: public class Class1 { public string Variable1 { get; se ...

Unable to retrieve the value of a specific property using _.map based on its property name

I'm currently facing a challenge with my app that utilizes MongoDB as its database. Specifically, I am having trouble extracting property values from array variables. Despite using a _.forEach method to confirm the presence of data, I encountered diff ...

Trigger the execution of the second function upon the successful completion of the first

In the following code, my concept is to display: The clicked kingdom (clicked_id) initiates an attack on (clicked_id). https://i.stack.imgur.com/Bx8QW.png https://i.stack.imgur.com/Cg2GL.png https://i.stack.imgur.com/gUNxM.png How can I trigger the sec ...

Using AJAX call and jquery each loop to work with JSON syntax

I made an AJAX request that fetches data from PHP. echo json_encode($json_response); The output looks like this: [{"name":"Sprouts.......}] Next, I used JQUERY to iterate through the data using the following code: $.each($.parseJSON(data), function(i, ...

Google script integrated with the Skyscanner Flights API

I am currently in the process of familiarizing myself with using the Skyscanner Flights API through Google Script. Unfortunately, most of the resources available online are quite complex for beginners like me. From what I understand, the steps to access f ...

Could anyone provide some insight into the reason behind this occurrence?

I just came across the most peculiar situation I've ever experienced. Check out this unique test page: <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <script language=javascript> fun ...

Implementing stop loss with node-binance-api: A step-by-step guide

Currently utilizing node-binance-api for trading purposes. I have initiated an order by executing the following lines of code: let adjustLeverage = await binance.futuresLeverage(coin, 2); let res_2 = await binance.futuresMarketSell(coin, quantity); . Subs ...

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...

AngularJS and ExpressJS clash in routing (Oops, Crash!)

When setting up routing in angularjs and expressjs, I have created app.all('/*'...) to enable rendering index.html. However, whenever I use /*, the page crashes with an "Aw, Snap!" message. angularjs home.config(function($routeProvider,$locatio ...

Change a Typescript class into a string representation, utilizing getter and setter methods in place of private variables

Below is a snippet of TypeScript code: class Example { private _id: number; private _name: string; constructor(id: number, name: string) { this._id = id; this._name = name; } public get id(): number { return t ...

JSON failed to provide me with a complete format

I am currently working on creating a JSON object, but I'm facing an issue with the format. It seems to only include the first property of "User" and the last property "item," instead of providing me with the complete JSON structure. Any help or guidan ...

What's the best way to capture an element screenshot using JavaScript?

I'm working on developing a unique gradient selection application. One of the exciting features I would like to incorporate is the ability for users to save their chosen gradients as digital images (.jpg format) directly onto their computers. When the ...

The onCall function in Firebase's realtime database does not provide a response data object when executing the remove() operation

When using onCall to perform a remove operation from a realtime database, I encountered an issue where the response only returned null instead of the expected data object. Strangely, I have used onCall for other operations like update and always received a ...

When transitioning to an object, Vue.js fails to refresh

My component contains an object called elements: elements: { id: { text: '', color: '', ... } To modify it, I use: <a-textarea autoFocus placeholder="text to include" :style="{ width: &ap ...