【问题标题】:Iterate over a dynamic table - Angular 11迭代动态表 - Angular 11
【发布时间】:2022-01-06 09:39:01
【问题描述】:

在我的项目中,我从 API 返回一个数据表。我正在尝试遍历一列并使每一行都有自己的命名值,以供以后使用。但由于每次调用的数据都可能不同,我不确定如何最好地做到这一点。

if(this.storedData.Table2.length != null)
    {
      let sum = this.storedData.Table2[0];
      let sum1 = this.storedData.Table2[1];
      let sum2 = this.storedData.Table2[2];
      let sum3 = this.storedData.Table2[3];
      let sum4 = this.storedData.Table2[4];
      if(sum.DataId = '4')
      {
        //do logic here
      }

但我永远不知道会有多少行,所以几乎不可能为每一行制定逻辑。有没有办法我可以做一个 forloop 或其他东西来动态地为每一行添加一个名称?

【问题讨论】:

    标签: angular for-loop dynamic


    【解决方案1】:

    我个人会使用forEach 并将每个变量存储在一个对象上,如下所示:

    const sums = { [key: string]: <insert type of each Table2 item> }
    
    if (this.storedData?.Table2?.length)
        {
          this.storedData.Table2.forEach((tableItem, index) => 
            sums[`sum${index || ''}`] = tableItem
          )
          
          if(sums.sum.DataId = '4')
          {
            //do logic here
          }
    ...
    

    这将为您构建一个动态对象字典,但我不确定您想对代码的if 语句和do logic here 部分做什么。请您详细说明一下您的要求吗?

    【讨论】:

    • 我无法让这些作品发挥作用,你能解释更多背后的原因吗? if 语句只是将值分配给其他函数和 html 标记的输入。
    • 我已经更改了答案,您需要使用forEach 而不是map。无论从 API 返回多少项目,它都会迭代并创建 sums 对象,每个项目都存储在该对象中。
    猜你喜欢
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多