Tips for calculating the total sum of inner object property values using JavaScript, TypeScript, or Angular 5

What is the total sum of successCount values in the given array object? var successCount;//I want count of all successCount attributes from the below object

var accordianData = [
  {
    name: "Start of Day",
    subItemsData: [
      {
        title: "Position",
        items: [
          { title: "XYZ",successCount:3,warningCount:1,status:"success"},
          { title: "ABC",successCount:3,warningCount:1,status:"success"},
          { title: "DDD",successCount:3,warningCount:1,status:"success"},
          { title: "ABCD",successCount:10,warningCount:1,status:"success"}
        ]
      },
      {
        title: "Trades",
        items: [
          { title: "DDD",successCount:3,warningCount:0,status:"success"},
          { title: "DDD",successCount:30,warningCount:0,status:"success"}
        ]
      }
    ]
  }];

Answer №1

Discovering a versatile solution that can navigate through your data, regardless of its structure, and calculate the total sum of successCounts wherever they are located.

const recurse = (totalSum: number, currentNode: any): number =>
  typeof currentNode === 'object' 
    ? Object.keys(currentNode).map(key => currentNode[key]).reduce(recurse, totalSum + (currentNode['successCount'] || 0))
    : Array.isArray(currentNode) ? currentNode.reduce(recurse, totalSum) : totalSum

alert(recurse(0, accordianData));

Answer №2

Utilize the Array.reduce method

var accordionContent = [{name:"StartofDay",subItemsData:[{title:"Position",items:[{title:"XYZ",successCount:3,warningCount:1,status:"success"},{title:"ABC",successCount:3,warningCount:1,status:"success"},{title:"DDD",successCount:3,warningCount:1,status:"success"},{title:"ABCD",successCount:10,warningCount:1,status:"success"}]},{title:"Trades",items:[{title:"DDD",successCount:3,warningCount:0,status:"success"},{title:"DDD",successCount:30,warningCount:0,status:"success"}]}]},{name:"IntraofDay",subItemsData:[{title:"Position",items:[]},{title:"MarketData",items:[]},{title:"Trades",items:[]}]}];
  
let successCount = accordionContent.reduce((a, {subItemsData}) =>
    subItemsData.reduce((ac, {items}) => 
      items.reduce((acc, v) => 
        v.status === "success" ? acc + v.successCount : acc
      , ac) 
    ,a)
  , 0);
  
  console.log(successCount);

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

Can you tell me the name of the Javascript "protocol" or "custom" being referred to here?

From what I can gather, the requests array seems to consist of functions with unique formatting and syntax. However, I'm struggling to find relevant search terms to help me better understand it: var requests = { rewardPoints: function(cb) { io ...

`Discover the latest version of Tailwind using JavaScript or PHP`

My setup includes Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30, and Tailwind https://i.sstatic.net/fVbJB.png I am looking to fetch the Tailwind version in JavaScript similar to how I can get the Vue version using: //app.js require('./bootstrap'); ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

Using React Refs to Trigger the video.play() Method - A Step-by-Step Guide

Is there a way to use a ref in order to trigger video.play()? Currently encountering an error: preview.bundle.js:261916 Uncaught TypeError: _this2.videoRef.play is not a function Take a look at my component: import React from 'react'; import s ...

Is it possible to retrieve the selected DataList object in Angular 10?

I encountered an issue while creating an Input field with DataList. My goal was to retrieve the entire object associated with the selected option, but I could only access the selected value. Previous suggestions mentioned that DataList items should be uniq ...

Utilizing Filestack in Angular 2

I'm currently working on integrating image uploading functionality into my Angular 2 App, and I have decided to utilize Filestack (formerly filepicker.io) for storing the images. Following Filestack's recommendations, I added the necessary script ...

Karma error `An unhandled exception occurred: Cannot locate module ‘karma’` is encountered during Jest Angular testing

Looking to implement Jest testing in my Angular project, I have followed all the setup instructions provided here. Here is an excerpt from my package.json: { "name": "jest-test", "version": "0.0.0", ... } Additionally, here ...

typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach. If I were to implement type checking for arguments that have been destructed multiple levels deep, ...

Guide to exporting (and using) JSDoc annotations in TypeScript NPM packages

Looking to enhance my skills in creating npm packages with TypeScript. I have a small project available at https://www.npmjs.com/package/lynda-copy-course/, and so far, the project structure is successful in: being executable from the command line after ...

The issue encountered during the construction of the nrwl library project is that object Object is not recognized as a PostCSS

We are currently facing an issue with our nrwl-nx workspace library project (based on Angular 8) that contains 3-4 angular libraries. While the ng serve function works properly, we have started encountering errors when trying to run ng build my-lib. On ou ...

Encountering a situation where the data retrieved from Firestore in Angular TypeScript is returning as

I am encountering an issue with retrieving the eventID value from my Events collection in Firestore. Although I am able to successfully display all the events in my app, I require the eventID for additional functionalities. As someone new to TypeScript an ...

Issues with nested array filtering in JS/Angular causing unexpected outcomes

I am faced with a particular scenario where I need to make three HTTP requests to a REST API. Once the data is loaded, I have to perform post-processing on the client side. Here's what I have: An array of "brands" An array of "materials" An array o ...

The Jade variable assignment variable is altered by the Ajax result

Seeking a solution to update a Jade variable assigned with the results of an ajax post in order for the page's Jade loop to utilize the new data without re-rendering the entire page. route.js router.post('/initial', function(req, res) { ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

Utilizing Google Caja for JavaScript sanitization is the only way to ensure

Looking to safeguard the inputs provided to a nodejs server with the assistance of the google-caja sanitizer. However, it's somewhat overzealous and cleanses away the > and < symbols too. My project requires me to retain html characters in the ...

Executing NPM commands in a sequential manner

If I have the following npm scripts: "scripts": { "pre-build": "echo \"Welcome\" && exit 1", "build_logic": "start cmd.exe @cmd /k \"yo esri-appbuilder-js:widget && exit 1\"", "post_build": "start C:\ ...

The child component is not updating the v-model prop array of the parent component

In my current project, I have a main component called cms-custom-editor: <template> <div id="cms-custom-editor" class="cms-custom-editor"> <cms-editor-toolbar v-model:toggles="state.toggles"/> <d ...

Verify the changing text within a Span tag with the use of Selenium in Java

Can anyone assist me in creating a logic to verify a dynamic text? The text within the tag below is constantly changing (to 6 distinct words), and I need to validate if those 6 unique words match the expected text. Is there a method to do this verification ...

The error message "Uncaught TypeError: Cannot read property 'createDocumentFragment' of null" occurs when using Jquery in Django

Struggling to identify the issue with this code that was previously functioning but started malfunctioning after reorganizing the JavaScript at the bottom of the page. It keeps throwing this error: https://i.sstatic.net/fozqo.jpg The line triggering the e ...

Passing a variable from index.html to a script in Angular

I am attempting to pass the array variable 'series' to the script in HTML. Is there a way to do this? app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app ...