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

Tips for incorporating a Survey Monkey website embed into an Angular application

I have a Survey Monkey account with multiple surveys. I am trying to embed a survey from this website into my Angular website, which already has Bootstrap and jQuery added. I attempted to directly add the script in an HTML component, but it did not work. ...

What is the best method for replacing the current page in an Ionic app?

I am facing an issue with the following navigation flow: User lands on the Contacts page -> clicks on a button to navigate to the NewContact page using navController.push() method -> from there, user is directed to the ContactCreated page. How can I modi ...

Hello there! I am just starting to learn about Bootstrap and I'm excited to create a responsive layout that will be centered on the page

I am aiming for this specific layout design. Here is the current code snippet that I have: <div class="container"> <h2 class="title mt-3 mb-4">Title</h2> <div class="container"> <div class="row"> <div cl ...

Detecting Errors in Angular Components Using Observers

In my component, I have the following code: this.authService.login4(this.email, this.password) .pipe(first()) .subscribe( data => { console.log(data); }, error => { ...

Troubleshooting the "Request failed with status code 500" error when refreshing a page in a React application

Every time the page is reloaded, an error message pops up saying: Uncaught (in promise) Error: Request failed with status code 500. Here's the code in list.tsx: const [state, setState] = useState([]); const { getRoom } = useRoom(); const fe ...

What is the process for transforming a multi-dimensional array containing strings into a multi-dimensional array containing numbers?

I've got a unique structure of data composed of arrays with strings as seen below: [ 0: Array(1) 0: Array(6) 0: [5.379856, 43.252967] 1: [5.422988, 43.249466] 2: [5.425048, 43.245153] 3: [5.383804, 43.239 ...

Execute an Asynchronous Operation in NgRx After Triggering an Action

Please note that this is a question seeking clarification Instructions Needed I am currently working on dispatching an action to NgRx in order to add a task to a list of tasks. Additionally, I need to perform a put request to an API to save the changes ma ...

Sending an array of strings to the function is not allowed

I'm encountering an issue with the following function: function proc(unames: Array<string>){} When I attempt to pass the function the following input: import _ = require('lodash'); const usernames = _.flattenDeep([unames]).filt ...

The addControl function inside a for loop and async function is not properly assigning a value to the form

My goal is to iterate through an array, make a HTTP request, retrieve another array from it, and assign the selected object from the fetched array to a newly added Form Control in the form. This is how I approached it: for (let i = 0; i < typeaheadFiel ...

Is there a way to extract only the desired array object from a post API response using Angular's filtering mechanism?

I'm utilizing the getSearchBank() post API and receiving this particular response from it. This API provides me with a list of all banks stored in the database. (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: {bankId: '616c07ca9d ...

How can one trigger a service method in nestjs through a command?

I am looking to run a service method without relying on API REST - I need to be able to execute it with just one command ...

Implement Stripe API mocking using Jest in Node.js with Typescript

I'm having trouble simulating the Stripe API for testing purposes. Although I don't have much experience with mocking functions using jest, I've already extensively researched how to mock the Stripe API without success. My file structure is ...

"Utilizing Angular's dynamic variable feature to apply ngClass dynamically

Looking for guidance on Angular - color change on button click. The loop binding is functioning well with dynamic variable display in an outer element like {{'profile3.q2_' + (i+1) | translate}}, but facing issues with [ngClass] variable binding ...

What is the most effective way to retrieve the width and height of an oversized image in Angular?

After attempting to retrieve the image width using the ngAfterViewInit method, a result of width = 0 is returned due to the large size of the image. Is there a way to accurately determine the image width without relying on a setTimeout() function? For re ...

Angular 2: Issue with Table not Being Updated

https://i.stack.imgur.com/qLDUZ.png The UsersList component opens a new page upon clicking the table. https://i.stack.imgur.com/WwqIX.png After changing and saving user values, the updated value is not immediately reflected in the grid for the first tim ...

Guide on assigning json array values to multiple accordion forms in Angular 6

Utilizing multiple accordion forms on the same page poses a challenge. When the Add button is clicked, an additional accordion form is added to the page. Upon submitting the second form, a set of JSON data is submitted. The resulting JSON array after three ...

Responsive MD-sidenav powered by Flex-Layout

I created an app using Angular and Flex-Layout, utilizing breakpoints to hide the navbar. Now I need to implement a click event to show the navbar when it is hidden. Here is what my code looks like: <md-sidenav-container> <md-toolbar> < ...

Should we be worried about the security of the RxJS library?

Currently, I am in the midst of a project utilizing RxJS within the Angular framework. A recent security evaluation flagged the use of window.postMessage(‘’, ‘*’) in our application as a potential vulnerability. Further investigation pinpointed Imm ...

Adjust the specific data type to match its relevant category

Is there a method to alter literal types in TypeScript, for instance. type T1 = ""; type T2 = 1 I am interested in obtaining string for T1 and number for T2. Regarding collections, I am unsure, but I assume it would involve applying it to the generic typ ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...