Reputation: 3198
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.
Upvotes: 1
Views: 287
Reputation: 3198
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');
}
}
Upvotes: 2
Reputation: 4236
I believe that when you are looping through accounts grouped by category, you should try group each category grouped item based on subcategory
like this;
this.accountList = _.groupBy(accounts, 'category');
_.foreach(this.accountList, function(categoryAccount) {
_.groupBy(categoryAccount, 'subcategory');
});
Upvotes: 0