Search code examples
javascriptarraysjavascript-objects

Aggregate values in a javascript grouped object based on conditions


I am using IE 11.

I have an object array that is grouped using the lodash library. I want to be able to query the object and based on certain conditions come up with sums/counts. So for example, I have this object array.

Object Array

I would like to have the result seen below but in an object like the image above enter image description here

As you can see, each company in the group should have certain values based on the following criteria

How many times does 'company x' have a Total Count >3? How many times does 'company x' have expectingFunding eq ‘Yes’> How many times does 'company x' have fundedOnIKNS eq ‘No’?

I've tried quite a bit in the last couple of days but not success. I first declared 2 arrays so I can capture the unique values of company name and program. I also created an object to update when conditions were met. The only successful thing I was able to get was to keep it in an grouped object. All the values in the new object were wrong.

Here's an excerpt of the code:

const companiesSummary = {};
for (const company of Object.keys(myData)) {
  companiesSummary[company] = {
    totalCount: 0,
    expectedFunding: 0,
    IKNSFunding: 0,
  };

  for (const { TotalCount, expectedFunding, fundedOnIKNS } of myData[company]) {
      companiesSummary[company].totalCount += TotalCount;
      companiesSummary[company].expectedFunding += expectedFunding === "Yes";
      companiesSummary[company].fundedOnIKNS += fundedOnIKNS === "Yes";
  }
}   

I get the error,

TypeError: myData[company] is not iterable

Here's a link to the pen

I would still like the result to be in an object array, so I can create an html table later. Any help would be much appreciated. Thank you!


Solution

  • Your code isn't working because you're taking myData, an array, accessing myData[company], an object (company is 0, 1, ...), and you can't iterate through an object with for...of. myData is definitely not the same object in your screenshot.

    Your code excerpt might work if your myData object were the object in your screenshot.