Search code examples
javascriptangularlodash

Using a double groupBy in lodash


So I am trying to categorize an array of objects by a certain attribute. Using groupBy works great the first time. Now I need to loop through those groupings and group them again based on a separate attribute. I am having trouble with this can someone help me out?

TS

this.accountService.getAccountListWithBalance().subscribe(accounts => {
      this.accountList = _.groupBy(accounts, 'category');
      for (var property in this.accountList) {
        if (this.accountList.hasOwnProperty(property)) {
          this.accountList.property = _.groupBy(this.accountList.property, 'subcategory');
        }
      }

generateArray(obj){
    return Object.keys(obj).map((key)=>{ return {key:key, value:obj[key]}});
  }

HTML:

<ul *ngFor="let item of generateArray(accountList)">
  <strong>{{ item.key }}</strong>
  <li *ngFor="let i of item.value">{{i.name}}</li>
</ul>

The HTML isnt set for the next level of interation but I know it isnt working if I just console log the resulting object. Like I said its being sorted the first time just not the second time.


Solution

  • I was able to get it to work by just changing my syntax. Using [] instead of . so the working code is as follows.

    this.accountService.getAccountListWithBalance().subscribe(accounts => {
          this.accountList = _.groupBy(accounts, 'category');
          for (var property in this.accountList) {
            if (this.accountList.hasOwnProperty(property)) {
              this.accountList[property] = _.groupBy(this.accountList[property], 'subcategory');
            }
          }