【问题标题】:Using a double groupBy in lodash在 lodash 中使用双重 groupBy
【发布时间】:2018-12-03 20:46:08
【问题描述】:

所以我试图按某个属性对一组对象进行分类。第一次使用 groupBy 效果很好。现在我需要遍历这些分组并根据单独的属性再次对它们进行分组。我遇到了这个问题,有人可以帮我吗?

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>

没有为下一级交互设置 HTML,但我知道如果我只是控制台记录结果对象,它就不起作用。就像我说的那样,它是第一次被排序,而不是第二次。

【问题讨论】:

  • 如果能分享账户服务api返回的json响应会很有帮助
  • 您的帐户模型的数据结构是什么?

标签: javascript angular lodash


【解决方案1】:

我只需更改我的语法就可以让它工作。使用[] 而不是. 所以工作代码如下。

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');
        }
      }

【讨论】:

    【解决方案2】:

    我相信,当您循环浏览按类别分组的帐户时,您应该尝试像这样根据subcategory 对每个类别分组项进行分组;

    this.accountList = _.groupBy(accounts, 'category');
        _.foreach(this.accountList, function(categoryAccount) { 
                  _.groupBy(categoryAccount, 'subcategory');
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多