Ways to retrieve the quantity of a particular value within an object using TypeScript

I'm inquiring about how to retrieve the number of a specific value within an object using TypeScript. Here is the structure of the object:

obj : TestObject = {
 name: "test",
 street: "test"
 subobj1: {
   status: warning,
   time: 11
   }
subobj2: {
   status: oki,
   time: 12
   }
subobj3: {
   status: warning,
   time: 13
   }
}

The TestObject interface is defined as follows:

export interface TestObject {

 name: string,
 street: string,
 subobj1: SubObj1,
 subobj2: SubObj2

}

My objective is to determine the count of objects with the "warning" status.

I am looking for a method that will return the count, which should be 2 in this case.

What should the code implementation look like?

Answer ā„–1

To begin, transform the object into an array of key-value pairs using Object.entries. Next, apply a filter function to set the condition, and finally count the length of the values to obtain the desired output!

let obj = {
  name: "test",
  street: "test",
  subobj1: {
    status: 'warning',
    time: 11
  },
  subobj2: {
    status: 'oki',
    time: 12
  },
  subobj3: {
    status: 'warning',
    time: 13
  },
}
console.log(Object.entries(obj).filter(([key, value]) => key.indexOf('subobj') > -1 ? value.status === 'warning' : false).length);

Answer ā„–2

const total = 0;
for (const key in object){
    if(object[key].status === "warning"){
        total += 1;
    }
}

Answer ā„–3

To achieve this task, you can utilize the forEach function applied to the array created by using the Javascript method Object.values.

let totalWarnings = 0;
Object.values(obj).forEach(value => {
    if(value.status == 'warning'){
        totalWarnings += 1;
    }
});

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

Issue with modal-embedded React text input not functioning properly

I have designed a custom modal that displays a child element function MyModal({ children, setShow, }: { children: JSX.Element; setShow: (data: boolean) => void; }) { return ( <div className="absolute top-0 w-full h-screen fle ...

Innovative techniques for class manipulation

Is there a way to implement type checking when extending a class with dynamic methods? For example, if you want to add methods to a class based on options provided to the constructor. This is a common scenario in plain JavaScript. const defaults = { dyn ...

Steps for creating a TypeScript project for exporting purposes

Forgive me for my lack of experience in the js ecosystem. Transitioning from static languages to typescript has been a positive change, though I still find myself struggling to grasp the packaging/module system, especially when coupled with typescript defi ...

Upgrade Angular to the most recent version available

Our organization is looking to upgrade our existing Angular version from v5 to either the latest version 12 or 13. After conducting some research, I believe that transitioning directly from 5 to 12-13 may be too significant. What would be the most effect ...

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

How can we eliminate the need for specifying the order of generic arguments in TypeScript?

In the development of my middleware engine, I have incorporated various generic arguments that are specific to the particular implementation in use. export type Middleware< Store = never, Args = unknown, Response = unknown > = ( context: { ...

What is preventing me from consistently accessing the Type Definition while my cursor is on a JavaScript/TypeScript parameter name in VS Code, and what are some strategies I can use to overcome this issue?

Imagine I have the following code snippet in my VS Code: type T1 = { x: number }; type T2 = { x: number } & { y: string }; function foo(arg1: T1, arg2: T2) {} If I place my cursor on arg1 and go to the type definition (either through the menu or a sh ...

Update Observable by assigning it a new value of transformed information using the async pipe and RXJS

My service always returns data in the form of Observable<T>, and unfortunately, I am unable to modify this service. I have a button that triggers a method call to the service whenever it is clicked. This action results in a new Observable being retu ...

When using TypeScript, my sorting function returns a value of 0 for all time values

I have been trying to sort this JSON data by date using the provided code, but it does not seem to work as expected. Below is a snippet of my JSON: { "StatusCode":0, "StatusMessage":"OK", "StatusDescription":[ { "id":"1", ...

Excessive wait times during the construction of a moderately sized application (over 2 minutes) using TypeScript and loaders like Vue-Loader and TS-Loader

I'm currently utilizing Nuxt 2 with TypeScript and the most up-to-date dependency versions available. Even though my app is of medium size, the compilation time seems excessively slow. Here are my PC specs: Ryzen 7 2700X (8 Cores/16 Threads) 16 GB D ...

Utilizing nested endpoints in Angular resource with a Node.js server

In my Angular application, I have a resource called /cars with the endpoint defined as $resource('/cars/:carsId'); This allows me to retrieve all cars or a specific car. On the server side, I've implemented middleware to ensure that carsI ...

Typescript has a knack for uncovering non-existent errors

When I attempted to perform a save operation in MongoDB using Mongoose, the code I initially tried was not functioning as expected. Upon conducting a search online, I came across a solution that worked successfully; however, TypeScript continued to flag an ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

The art of representing objects and generating JSON responses

As I dive into building a web application using NextJS, a versatile framework for both API and user interface implementation, I find myself pondering the best practices for modeling and handling JSON responses. Key Points In my database, models are store ...

How can you determine if an API method call has completed in Angular and proceed to the next task?

Two methods are being used for api calls in my code. Method one is calling out method two and needs to wait for method two's api call to finish before continuing with its own process. I attempted to achieve this using the complete function inside a su ...

IntelliJ fails to detect Angular Material HTML tags

Embarking on a new project from scratch using Angular 5 and Angular Material. Encountering an issue with IntelliJ not recognizing Angular Material HTML tags: import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from &apos ...

Tips for inserting an object into an array

Here's the data I received: { 0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 } 1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60} 2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60} item ...

Storing multiple strings in a string array in Angular2

Hi everyone, Iā€™m just getting started with Angular and currently working on creating a recipe page that fetches data from an API. The API setup is complete, but now I need to figure out how to input the data into the API using Angular. I have defined a ...

Why is Typescript converting my keyof type to a never type and what steps can I take to resolve this issue?

Apologies if this question is repetitive, as I am new to TypeScript and struggling to identify related issues due to the complexity of some questions. The issue I'm facing involves TS coercing a type to never, which is confusing me. Here's the sc ...

Swapping out the standard if/else logic for try/catch error

I'm facing a challenge in removing the then statements from this code snippet and replacing all catches with try/catch statements. I'm struggling to figure out how to handle the then statements. export class WelcomePageContribution implements IW ...