Is there a way to sum up the values in my object without having to use Object.entries within?

Here is a snippet from my JSON data:

const jsonData = {
  "08/23/2022": {
    "One": 254,
    "Two": 92,
    "Three": 8
  },
  "08/13/2022": {
    "One": 327,
    "Two": 86,
  },
  "08/14/2022": {
    "One": 431
  },
}

I am looking to calculate the sum of all the values in this JSON object, regardless of the keys. For example, in this case, the total sum would be 254+92+8+327+86+431, resulting in 1198. Initially, I was only considering the first value, but I realized that approach is incorrect. I am currently using a nested loop in my code to achieve this, as shown below:

let sum = 0;
for (const [key, value] of Object.entries(jsonData)) {
  Object.entries(value).forEach(val => sum += val[1])
}

Is there a more efficient or cleaner way to accomplish this task?

Answer №1

When dealing with nested objects, there are essentially two layers to navigate - the date-object pairs at the top level, and then the digit-number pairs within each inner object. It becomes clear that addressing this two-level nesting scenario requires a logical approach.

A more efficient strategy would involve utilizing Object.values - focusing solely on the values without concerning oneself with the keys.

const json = {
  "08/23/2022": {
    "One": 254,
    "Two": 92,
    "Three": 8
  },
  "08/13/2022": {
    "One": 327,
    "Two": 86,
  },
  "08/14/2022": {
    "One": 431
  },
};
const sum = Object.values(json)
  .flatMap(Object.values)
  .reduce((a, b) => a + b, 0);
console.log(sum);

The total sum is 1198, derived from adding up all the values: 254+92+8+327+86+431.

Although it's possible to iterate through nested properties by using JSON.stringify, this method is not recommended for real code as it involves iterating over all nested properties, making it an impractical approach.

const json = {
  "08/23/2022": {
    "One": 254,
    "Two": 92,
    "Three": 8
  },
  "08/13/2022": {
    "One": 327,
    "Two": 86,
  },
  "08/14/2022": {
    "One": 431
  },
};
let sum = 0;;
JSON.stringify(json, (_, val) => {
  if (typeof val === 'number') sum += val;
  return val;
});
console.log(sum);

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

"Automate the process of manual content duplication with JavaScript's for each replacement

Seeking a solution to automate the selection process without writing individual JS scripts for every input. For instance, having 10 double inputs (total of 20 inputs) and utilizing the each() function or other methods by only declaring selectors. Find th ...

Sending a JSON object in Swift without using the traditional "key - value" pair formatStringEncoding in Swift without the usual "key

Hello there, I'm facing an issue where I need to send a token string to the Django-server but it only accepts one string at a time. I've been attempting to use alamofire for this task, however, I'm unable to send a key-value pair to solve th ...

Having trouble displaying Ad-Gallery Loader.gif?

Having trouble with an image gallery I found at . The loader.gif image isn't showing up in IE9, just a red X. Being new to JavaScript, I'm struggling to fix this issue located at the top of the JavaScript file. (function($) { $.fn.adGallery = ...

When attempting to modify the date and time input within the table, I find that as soon as I begin typing the first number, it automatically triggers the edit mode

Is it possible to modify the input date and time within the table without triggering any actions until both values have been entered? The entered value should be displayed within the table for editing purposes. Here's an example: function myFuncti ...

Tips on tallying the frequency of items in a state array

I'm currently working on an application in which clicking a button adds the item's value to the state. The button is clickable multiple times, allowing the same item to be added multiple times in the state array. My current code snippet: export ...

Send the data from a table row to an AJAX request using JSON format when a checkbox is selected in a VB.NET

Looking for assistance on how to pass selected row data using AJAX JSON to VB.NET code in the code-behind. My table has 7 columns of data and I am using checkboxes to select multiple rows. Any suggestions on how to achieve this? Any help would be greatly ...

Troubleshooting a Problem with the Horizontal Scrollbar in Dynamic jqGrid

Currently, I am working on an ASP.net MVC project where I have implemented both dynamic and static jq grids. However, I am encountering an issue with the horizontal scroll bar in my application. To address this problem, I attempted to modify the overflow ...

Failed verification of C-Lang in React-Hardware/Particle

Currently, I am utilizing React, React Hardware ([https://github.com/iamdustan/react-hardware/]), and Johnny-Five along with the Particle Photon. The error stack displayed below is what pops up when executing my lib/app.js file: # Fatal error in ../deps/v ...

Sharing data between two components on the same level in Vue.js

I have a situation where I need to transfer data from one component1 to another component2. I am not utilizing vuex or router for this task. The component tree looks like this: -Parent --Component1 --Component2 In the first component1, I am sending an ...

Is there a way to prevent a web page from automatically refreshing using JavaScript?

I would like my webpage to automatically refresh at regular intervals. However, if a user remains inactive for more than 5 minutes, I want the refreshing to stop. There is an example of this on http://codepen.io/tetonhiker/pen/gLeRmw. Currently, the page ...

Delivering resources through the Nuxt configuration file

https://i.stack.imgur.com/2OWdE.png I came across a bootstrap template online that I want to customize for my Nuxt project. I have stored all the bootstrap files in the static folder. Within the nuxt.config.js file: module.exports = { /* ** Headers ...

Looking to display or conceal a text box with a date picker based on the selection of a specific value from a drop-down menu

I have a dropdown with two options: Indian and Others. When I select Others, I want to display three textboxes - two with date pickers and one with a simple text input field. I have tried writing the following HTML code but I am unable to get the date pick ...

Having trouble with a JavaScript function and tag that don't seem to be working in Chrome, but function well in Mozilla Firefox. Can anyone provide assistance with

Below is the code for creating two dropdowns: one for "Property Type" and the second for "Property Sub Type". This code works fine in Firefox but not in Chrome. When selecting "residential" as the property type, only residential values will appear in the ...

Executing code after sending an HTTP response in Next.js: A comprehensive guide

Executing code after sending an HTTP response in Express can be done like this: res.send() await someAsyncFunction() // assuming this function takes a significant amount of time In the case of Next.js, testing locally shows that the above code behaves sim ...

Troubleshooting: Why is my Local Image not displaying in ReactJS

I am facing an issue with displaying images in my React application using an array of image paths. Below is the code snippet I have written: import React, { Component } from 'react'; class ItemsList extends Component { constructor() { ...

Having trouble with loading a new page on an HTML website

My website is successfully updating the database, printing all values, but for some reason the new page is not opening. The current page just keeps refreshing and I'm receiving a status of 0. Below is my code snippet: try{ console.log("here1 "+e ...

What is the best way to showcase Json API content on an HTML page?

I possess a strong proficiency in html and css, however I lack experience in utilizing javascript. My aim is to showcase the date received from an API onto an html page Despite several attempts, I have not been able to achieve success yet. var getJSON ...

I desire to perform a specific task when there is a modification in the path using react router framework

Though I am mindful of it. props.history.listen((location, action) => { console.log("when route changes",location); }) However, I need to implement it in a slightly different way. For instance, let's cons ...

Issues with AngularJS ng-bind-html failing to display list items

I am working with a basic HTML document that looks like this... <ol> <li><strong>Test 1</strong></li> <li><strong>Test 2</strong></li> </ol> ...and I am attempting to connect it to a div ...

Vue.js methods bound as properties on a parent object

There are times when I come across scenarios where it would be convenient to bind methods as an object property rather than a direct Vue method. For instance, instead of: <MyInput :formatter="currencyFormat" :parser="currencyParser& ...