Search code examples
javascriptarraysloopsjavascript-objects

How do I loop through a javascript Array in a React App that has object and get a count on a property that has a certain value


I have this javascript array that has objects nested with in it.

[{
    "MonitoringState": "disabled",
    "State_Code": 16,
    "State_Name": "running",
    "EbsOptimized": false,
    "EnaSupport": true,
    "SourceDestCheck": true,
    "SpotInstanceRequestId": "None",
    "SriovNetSupport": "None",
    "StateReason_Code": "None",
    "StateReason_Message": "None"
  },
  {
    "MonitoringState": "disabled",
    "State_Code": 16,
    "State_Name": "stopped",
    "EbsOptimized": false,
    "EnaSupport": true,
    "SourceDestCheck": true,
    "SpotInstanceRequestId": "None",
    "SriovNetSupport": "None",
    "StateReason_Code": "None",
    "StateReason_Message": "None"
  },
  {
    "MonitoringState": "disabled",
    "State_Code": 16,
    "State_Name": "running",
    "EbsOptimized": false,
    "EnaSupport": true,
    "SourceDestCheck": true,
    "SpotInstanceRequestId": "None",
    "SriovNetSupport": "None",
    "StateReason_Code": "None",
    "StateReason_Message": "None"
  },
  {
    "MonitoringState": "disabled",
    "State_Code": 16,
    "State_Name": "stopped",
    "EbsOptimized": false,
    "EnaSupport": true,
    "SourceDestCheck": true,
    "SpotInstanceRequestId": "None",
    "SriovNetSupport": "None",
    "StateReason_Code": "None",
    "StateReason_Message": "None"
  },
  {
    "MonitoringState": "disabled",
    "State_Code": 16,
    "State_Name": "running",
    "EbsOptimized": false,
    "EnaSupport": true,
    "SourceDestCheck": true,
    "SpotInstanceRequestId": "None",
    "SriovNetSupport": "None",
    "StateReason_Code": "None",
    "StateReason_Message": "None"
  },
  {
    "MonitoringState": "disabled",
    "State_Code": 16,
    "State_Name": "running",
    "EbsOptimized": false,
    "EnaSupport": true,
    "SourceDestCheck": true,
    "SpotInstanceRequestId": "None",
    "SriovNetSupport": "None",
    "StateReason_Code": "None",
    "StateReason_Message": "None"
  }
]

I want to loop through this and get the see the number of State_Name that are running and those that are stopped. I know I have 6 running and 2 stopped.

So I want my html to say "There are 4 running and 2 stopped". The object is actually bigger and I am doing this in a React App. I have a number of properties where I want to do the same thing. Just need a good pattern.

What is a good pattern at accomplishing this?


Solution

  • You could do something like this:

    const runningCount = records.filter(r => r.State_Name === 'running').length
    

    For stopped you can do:

    const stoppedCount = records.filter(r =>r.State_Name === 'stopped').length
    

    Then for your template, just do:

    <span>There are {runningCount} running and {stoppedCount} stopped. </span>
    

    The variable records is basically your array.