Summing values in es6 (TypeScript) without explicitly knowing their corresponding keys

I am facing a challenge with an object that has changeable keys, which I do not want to rely on. The keys in this object are not fixed. Here is an example:

interface Inf {
 [key: string]: number
}


const obj: Inf = {
  '2020-01-01': 4,
  '2020-01-02': 5,
}

const obj2: Inf = {
  '2020-01-05': 10,
  '2020-02-10': 15,
}

const finalObj = { one: obj, two: obj2, ... }

My goal is to calculate the sum of 10 + 15 + 4 + 5 regardless of their key names. I have lodash installed, which offers a method called sumBy. However, it requires input as an array, while mine is a full object.

Is there a way to achieve a total of 34 from this object efficiently? What would be the best approach for handling such an operation?

let x = 0

Object.values(obj).forEach(o => {
   x += o
})

While the above solution works, I'm curious if there is a better or more concise way to accomplish this task. Any suggestions for a shorter and faster implementation?

Answer №1

One way to handle nested objects is by using a recursive approach.

const
    calculateTotal = object => Object
        .values(object)
        .reduce((sum, value) => sum + (value && typeof value === 'object' ? calculateTotal(value) : value), 0),
    obj1 = { '2020-01-01': 4, '2020-01-02': 5 },
    obj2 = { '2020-01-05': 10, '2020-02-10': 15 },
    finalObj = { obj1, obj2 },
    totalSum = calculateTotal(finalObj);

console.log(totalSum);

Answer №2

If you're looking to calculate the sum of values in objects with only one level like in your provided example, you can employ Object.values along with reduce.

const obj = {
    "2020-01-01": 4,
    "2020-01-02": 5,
};
const obj2 = {
    "2020-01-05": 10,
    "2020-02-10": 15,
};
const finalObj = { one: obj, two: obj2 };

const result = Object.values(finalObj).reduce((a, b) => a + Object.values(b).reduce((a1, b1) => a1 + b1, 0), 0);

console.log(result);

Answer №3

In the comments, you specified that you are only working with a single layer (as indicated in the question). My approach would involve using a straightforward nested loop:

let sum = 0;
for (const obj of Object.values(finalObj)) {  // Iterate through the objects
    for (const value of Object.values(obj)) { // Iterate through the values
        sum += value;
    }
}

This method closely resembles Nikita's solution, but with explicit loops. :-)

See a live example below:

const obj = {
    "2020-01-01": 4,
    "2020-01-02": 5,
};
const obj2 = {
    "2020-01-05": 10,
    "2020-02-10": 15,
};
const finalObj = { one: obj, two: obj2 };

let sum = 0;
for (const obj of Object.values(finalObj)) {
    for (const value of Object.values(obj)) {
        sum += value;
    }
}

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

Checking with Protractor to see if the modal is displayed

I am currently working on a Protractor test to check if a bootstrap modal window that confirms the deletion of a record is visible at this time. The record that needs to be deleted is displayed in an angular ng-repeat, so I have to trigger the delete butt ...

Trouble accessing Silverlight site due to incomplete loading

There is a site known as that consists of a Silverlight application. Strangely, this site loads on all other computers except mine. I keep encountering the following error: An Error occurred in the Silverlight Application: String was not recognized as a ...

The bond between TypeORM and express

I am working on establishing Many-to-One and One-to-Many relationships using TypeORM and MySQL with Express. The database consists of two tables: post and user. Each user can have multiple posts, while each post belongs to only one user. I want to utilize ...

What is the best way to represent a state with two possible fields in React using TypeScript?

There is a specific state item that can have its own value or reference another item using an ID. interface Item { itemName: string; itemValue: { valLiteral: number } | { idNumber: string }; } const indItem1: Item = { itemName: "first sample&quo ...

Adjusting the filter location in React-admin

This is the common method of implementing filters in react-admin https://i.stack.imgur.com/M8yq7.png However, in my particular scenario, I require the filters to be inside each column heading. For example: https://i.stack.imgur.com/GU2Pz.png The filter ...

Utilizing the content of an HTML element within Ruby embedded code - a comprehensive guide

Below is the code snippet in question: <% @groups.each do |group| %> <tr> <td id="groupid"><%= group.id %></td> <td><a href="#dialog" name="modal"><%= group.title %></a></td> </tr> &l ...

I'm perplexed as to why I'm receiving null for my context. Could it be due to a TypeError

Recently diving into Next Js and TypeScript, I encountered the following error: Unhandled Runtime Error TypeError: this.context is null Here's a snippet from my Layout.tsx file: import { FC } from 'react' import { Head } from 'next/d ...

AngularJS Unleashed: The Art of Displaying Dynamic AJAX

Hey there, I have a concern about the best practice to show or hide an ajax loading animation while input/output operations are being performed. At present, I am managing the animation using this code: Javascript app.controller('MyController', ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Using a template reference variable as an @Input property for another component

Version 5.0.1 of Angular In one of my components I have the following template: <div #content>some content</div> <some-component [content]="content"></some-component> I am trying to pass the reference of the #content variable to ...

Technique in CSS/SASS to repair a div

Seeking a solution for fixing divs with text in CSS. I am aware of the background-attachment: fixed; property which creates a fancy effect. Is there a similar property to "fix" divs with text or how can this be achieved in Typescript? Your insight would be ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

I am having trouble resolving 'otp-input-react' in my project directory at D:projectappsrc

I have been troubleshooting this issue but haven't been able to find a solution yet. I even tried uninstalling and reinstalling the package, but it still isn't working as expected. Here are some images for better clarity: https://i.stack.imgur.c ...

Executing Controller Actions within a JavaScript Timer

Presenting my latest timer: var eventDate = new Date(Date.parse(new Date) + 3600); function countdown() { var elapsed = Date.parse(eventDate) - Date.parse(new Date()); var seconds = Math.floor((elaps ...

Managing errors with async/await in an Angular HttpClient function

I have been experimenting with an async/await pattern to manage a complex scenario that could potentially result in "callback hell" if approached differently. Below is a simplified version of the code. The actual implementation involves approximately 5 co ...

Utilize jQuery Function on Identical Class of <ul> Elements

I have integrated a listview control in my ASPX page. The data is being fetched from the database and displayed in the listview. I have also utilized jQuery script to implement the .fadein() and .fadeout() effects on the listview elements. However, when I ...

When attempting to integrate Angular 1.4's new router with components, an issue arises where a warning is triggered stating, "Failed to instantiate controller HeadlinesController

Attempting to work with Angular for the first time and struggling to load a component using data from an http request. Currently encountering a warning when attempting to execute the code with the HTTP request. Receiving a "Could not instantiate control ...

Guide to integrating the Braintree API with Node.js

I am trying to implement Braintree for website payment gateway, but I encountered an issue while following the online guidelines. The code seems to be incompatible with Node.js. Am I missing something? Index.js: //send token to clients app.get("/client_t ...

Angular Translate Directive Unleashes the Power of XSS Vulnerabilities

For my project, I have chosen to utilize the 'escape' method as the sanitization strategy for handling potentially harmful content. This includes implementing the translate directive in certain areas, as well as utilizing the translate filter in ...

Bringing Angular ECharts into a Stackblitz 15.1 setup: A How-To Guide

Recently, Stackblitz made a change to use a standalone configuration for Angular Projects. However, when trying to initialize the module for Angular ECharts (ngx-echarts), an error occurred: Error in src/main.ts (18:5) Type 'ModuleWithProviders<Ngx ...