【问题标题】:GroupBy and Sum Typescript restructure Rest APIGroupBy 和 Sum Typescript 重构 Rest API
【发布时间】:2021-11-20 22:24:33
【问题描述】:

需要帮助!!!!我正在尝试在 api 端点中重构对象。所以,我所做的是创建了一个调用服务的方法,如下所示:

getData() {
    this.branchService.getBranchPipeline()
    .subscribe(res => {
      console.log(res);
      this.branches = res;

      let datas = this.branches;

      this.dataProduct = datas.reduce((unit: any, item: any) => {
  
        let unitItem = unit.find((u: any) => u.fields['Fields.CUST01FV'] === item.fields['Fields.CUST01FV']);
        
        if(unitItem){
          unitItem.fields['Fields.16'] += Number(item.fields['Fields.16']);
          unitItem.fields['Loan.LoanAmount'] += Number(item.fields['Loan.LoanAmount']);
        }else{
          unit.push(item)
        }
        return unit;
      },[])
      
      console.log(this.dataProduct)
    })
  }

我想要做的是 groupby 和 sum,所以我可以在一个看起来像这样的表格中创建一个报告:

Image of UI

发生的事情是连接而不是给我总和。我在这里做错了什么?

【问题讨论】:

  • 看起来 Loan.LoanAmount 和/或 Fields.16 的值是一个字符串,对于具有特定 Fields.CUST01FV 的第一项,您将对象直接放在数组中。具有相同 Fields.CUST01FV 的后续项目在连接的两个(字符串)值上使用 +=。首次将项目添加到数组时,您可能应该使用 Number(...) 或 parseInt 解析字段,而不是按原样添加。
  • @Mack 这正是正在发生的事情。你觉得你能给我举个例子吗?
  • 看起来现有值可能是一个字符串。尝试铸造它。 unitItem.fields['Fields.16'] = Number(unitItem.fields['Fields.16']) + Number(item.fields['Fields.16']);
  • 是的,这行得通。谢谢本!!

标签: angular typescript api rest


【解决方案1】:

似乎传递给您的代码的数据将字段存储为字符串,因此当您将对象按原样存储为具有给定 ID 的第一个项目时,该值仍保留为字符串,随后的金额将连接到该字符串(在 Javascript 中,string += number 将返回一个字符串。)

我们可以通过构造一个新对象来解决这个问题,而不是将相关计数器存储为数字。

与其每次都在数组中搜索具有匹配“Fields.CUST01FV”的项目,还不如使用将此 ID(作为键)映射到 sum 对象(作为值)的对象更有效。

为这个“sum 对象”定义一个类型来强制类型安全可能是个好主意。

getData() {
  this.branchService.getBranchPipeline().subscribe((res) => {
    console.log(res);
    this.branches = res;

    let datas = this.branches;

    this.dataProduct = datas.reduce((unit: any, item: any) => {
      // look up an existing sum item by it's CUST01FV 
      let unitItem = unit[item.fields["Fields.CUST01FV"]];
      
      // if we have an existing "sum" item, add to the totals
      if (unitItem) {
        unitItem.field16 += Number(item.fields["Fields.16"]);
        unitItem.loanAmount += Number(item.fields["Loan.LoanAmount"]);
      } else {
        // otherwise, store initial totals from this item
        unit[item.fields["Fields.CUST01FV"]] = {
          field16: Number(item.fields["Fields.16"]),
          loanAmount: Number(item.fields["Loan.LoanAmount"]),
        };
      }
      return unit;
    }, {});

    console.log(this.dataProduct);
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 2019-09-29
    相关资源
    最近更新 更多