0

I need help not sure what I'm missing. I am trying to loop through an array of objects in Angular to find count of a specific field in objects. For instance I want to find out how many ID's came in with the risk of 'Moderate', 'High','Low'?

I can count the total amount of objects for having trouble counting the number of risks associated with a type of risk like 'Moderate'

json:

[ 
{"id": 1, 
 "risk": "Moderate"
},
{"id": 2, 
 "risk": "Low"
},

{"id": 3, 
 "risk": "Moderate"
},
{"id": 4, 
 "risk": "High"
}]

component.ts

countTotalChanges() {
    let count = 0; 

        for (var i = 0; i < this.changeService.length; i++) {
            count++; 
    }
    return count;
  }

HTML

{{countTotalChanges()}}

1 Answer 1

3

If that array of objects is called items, for example, this will work:

items.filter(item => item.risk === 'Moderate').length

You can replace 'Moderate' with whichever risk type you want.

Sign up to request clarification or add additional context in comments.

2 Comments

sorry for my ignorance. Where would that be implemented?
In whichever function you're using to count the items based on risk type. So a function could be countItemsByRiskType(riskType: string) { ... } and in that function is where you use my above answer. Then, from my original answer, replace 'Moderate' with the variable riskType. Then you can call the function and pass in the riskType you want to count.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.