Attempting to employ the .reduce method on an object

Currently, I am faced with the task of summing a nested value for all objects within an object. The structure of my object is as follows:

const json = [
{
    "other_sum": "1",
    "summary": {
        "calculations": {
            "time": 10,
            "unit": 25
        },
        "updated": "2020-06-05"
    }
},
{
    "other_sum": "1",
    "summary": {
        "calculations": {
            "time": 20,
            "unit": 5
        },
        "updated": "2020-06-05"
    }
},
{
    "other_sum": "1",
    "summary": {
        "calculations": {
            "time": 5,
            "unit": 15
        },
        "updated": "2020-06-05"
    }
},
];

The objective is to calculate the total sum of all "unit" values present.

I have attempted using .reduce for this purpose, however, encountered an error when adding a third item to the object.

Below is the snippet of code I am currently working on:

const r = json.reduce((a, b) => a.summary.calculations.unit + b.summary.calculations.unit);
console.log(r);

Confused about what might be going wrong in my approach. Any help or guidance would be greatly appreciated.

Answer №1

Notably, the functionality of reduce doesn't align with that approach. Referenced from an insightful article, it operates as follows:

Given

arrSum = function(arr){
  return arr.reduce(function(a,b){
    return a + b
  }, 0);
}

The callback function passed to the reduce method takes two parameters, a and b. In this context, a acts as our accumulator, gradually accumulating the sum. Whereas, b represents the current value under process.

It seems like an attempt is being made to access "summary" within the accumulator which is solely a number. A functional snippet for reference:

json = [
{
    "other_sum": "1",
    "summary": {
        "calculations": {
            "time": 10,
            "unit": 25
        },
        "updated": "2020-06-05"
    }
},
{
    "other_sum": "1",
    "summary": {
        "calculations": {
            "time": 20,
            "unit": 5
        },
        "updated": "2020-06-05"
    }
},
{
    "other_sum": "1",
    "summary": {
        "calculations": {
            "time": 5,
            "unit": 15
        },
        "updated": "2020-06-05"
    }
},
];

const r = json.reduce((a, b) => a + b.summary.calculations.unit, 0);
console.log(r);

Answer №2

The initial argument given to the callback function used with .reduce serves as the accumulator, with the output of each iteration becoming the accumulator for the subsequent iteration.

As a result, the calculation applied to the next element will be

a.summary.calculations.unit + b.summary.calculations.unit
, and in the following loop, your callback will attempt to access the nested property a.summary.calculations.unit within that outcome, which may not be present.

You might consider modifying it to something like this:

const total = json.reduce((a, b) => a + b.summary.calculations.unit, 0);

Here, 0 signifies the starting value for your accumulator.

It's always beneficial to consult sources like Mozilla Developer Network (MDN).

Answer №3

The initial value passed to the reduce function is not an object; instead, it is the previous value that gets returned. To fix this issue, consider updating your code as shown below:

 json.reduce((total, b) => total + b.summary.calculations.unit, 0);

Answer №4

If you are looking for a solution, consider using the dig function I have created:

function dig(obj, func){
  let value;
  if(obj instanceof Array){
    for(let index=0,length=obj.length; index<length; index++){
      value = obj[index]; func(value, index, obj);
      if(typeof value === 'object')dig(value, func);
    }
  }
  else{
    for(let key in obj){
      value = obj[key]; func(value, key, obj);
      if(typeof value === 'object')dig(value, func);
    }
  }
}
const jsonData = [
  {
    "other_sum": "1",
    "summary": {
      "calculations": {
          "time": 10,
          "unit": 25
      },
      "updated": "2020-06-05"
    }
  },
  {
    "other_sum": "1",
    "summary": {
      "calculations": {
        "time": 20,
         "unit": 5
      },
      "updated": "2020-06-05"
    }
  },
  {
    "other_sum": "1",
    "summary": {
      "calculations": {
        "time": 5,
        "unit": 15
      },
      "updated": "2020-06-05"
    }
  }
];
let unitTotal = 0, timeTotal = 0;
dig(jsonData, (value, key)=>{
  if(key === 'unit'){
    unitTotal += value;
  }
  else if(key === 'time'){
    timeTotal += value;
  }
});
console.log('unitTotal: '+unitTotal);
console.log('timeTotal: '+timeTotal);

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

Updating a nested object within an array in a ReactJs component

I am struggling with updating a nested object within an array in the state of my React application. My goal is to determine if an item already exists in the state based on its name. Here's what I'm aiming for: Add an item to the cart. If th ...

Is it possible to utilize a computed property for dynamically styling a table row based on certain conditions?

I have a table of users that I am currently rendering, and my goal is to highlight the entire row only for the current user. My initial thought was to use a computed property to achieve this, but I seem to be facing some difficulties in making it work. I ...

Is there a way to efficiently navigate a local JSON file using React JS?

What is the best way to extract data from a JSON file and utilize it within my code? I attempted importing the file and logging it in the console, but all I get is Object {}: import jsonData from "./file.json"; console.log(jsonData); This is the content ...

What steps should I follow to change the appearance of this object to match this?

Attempting to modify the value of an object nested within an array, which is in another object. The nesting might be a bit complex... Here's how it currently looks { household and furniture: [{…}, {…}], school stuffs: [{…}, {…}] } M ...

Issue with AngularJS: Not able to get second app in template to function properly

I have encountered a puzzling issue with my two nearly identical apps. The first one seems to be running smoothly as expected, while the second one doesn't appear to be executing at all. Here is my code (jsfiddle): <div ng-app="passwdtool" ng-con ...

"Troubleshooting: Issue with AngularJS ng-repeat not functioning properly when using an

I am working with a simple list <ul> <li ng-repeat="spiel in spielListe">Do something</li> </ul> Along with a perfectly connected controller $scope.spielListe = []; There is also a method that adds objects to the array in th ...

Determining the Percentage of a Bar Chart

When utilizing Chart.js along with the fork available at (https://github.com/leighquince/Chart.js), I successfully developed a bar chart featuring 3 bars: Goal, Actual, and Available data. My challenge lies in finding a method to calculate the percentage ...

What is the best way to pass a state within a route component in react-router?

... import { useNavigate, NavigateFunction } from "react-router"; ... function Form(): JSX.Element { const navigateToCountry = (country: string) => { // Code to navigate to country page with the given country } const [selectedCount ...

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

React application no longer displaying content following the upgrade to React 18 version

My React App was functioning perfectly, but after updating to React 18, MUI v5, and Redux v5, it stopped rendering anything. When I check the terminal, it shows: "webpack compiled successfully" However, in the Chrome console, I see: Warning: In ...

I am experiencing difficulty with the color of my progress bar in Firefox

After successfully creating an interactive progress bar that works perfectly in Google Chrome and surprisingly also in Safari without vendor prefixes, I encountered a roadblock when testing it on Firefox. The progress bar color reverts back to the default ...

Oops! The system encountered a problem while trying to identify the value `Han` for the property `Script

I'm attempting to extract Chinese characters from a string. According to this particular answer, the following code snippet should work: const nonChinese = /[^\p{Script=Han}]/gimu; const text = "asdP asfasf这些年asfagg 我开源的 几 ...

Exploring the Battle of Efficiency: Stateless Components vs. Class Components in the Age of React Hooks - Determining the Superior Approach

Having delved into various online resources and discussions on platforms like Stack Overflow (link here), the consensus seems to lean towards utilizing stateless functions (functional components) whenever possible. Many of the life cycle methods found in ...

Pins missing from Google Maps API display

TLDR: The problem lies within the var marker = new google.maps.Marker() line. It seems that either the pins are not visible, incorrect, or simply not appearing. Background: I have implemented some JavaScript code that utilizes AJAX to fetch data on the ...

Sequelize Error: The WHERE parameter for 'email' is throwing an error due to an invalid value of 'undefined'

Currently, as part of my Node.js application, I am using Sequelize to develop a user registration feature. However, I seem to be facing an issue when attempting to verify the existence of a user based on their email address. The error that keeps popping up ...

The concept of inheriting directives/scopes

Just wondering if directives declared within a Component in Angular 2 automatically apply to its children Components. And when it comes to variables declared on the Component, do they get inherited by the children Components or must they be explicitly pa ...

What could be causing BeautifulSoup to overlook certain elements on the page?

For practice, I am in the process of developing an Instagram web scraper. To handle dynamic webpages, I have opted to utilize Selenium. The webpage is loaded using: driver.execute_script("return document.documentElement.outerHTML") (Using this javascript ...

Vue.js Conditional Templates

I am attempting to implement VueJs conditional rendering using handlebars in vueJs 2.0 as outlined in their official documentation, but eslint is throwing an error: - avoid using JavaScript keyword as property name: "if" in expression {{#if ok}} - avoid us ...

Transferring data from a JavaScript variable to PHP using AJAX

I’m currently working through the tutorial at http://www.w3schools.com/php/php_ajax_database.asp and I think I have a good grasp of how it all operates. This is my code: PHP: <?php include('./db.php'); $PM = mysqli_query($con, "SELECT DIS ...

What could be causing my Material UI Divider to appear invisible within a Material UI Container or Paper component?

Hey there! I am absolutely smitten with Material UI - it's incredibly versatile. However, I'm facing a bit of trouble with the Material UI Divider not displaying when nested within either a Container or Paper component. I've looked into it ...