【问题标题】:How to loop through nested arrays in Angular如何在Angular中循环嵌套数组
【发布时间】:2018-12-22 12:04:30
【问题描述】:

我有一个这种形式的嵌套数组

tests: [
  [{name:"Bob",score:40,subject:"Math"}, {name:"John",score:55,subject:"Math"}],
  [{name:"Alice",score:70,subject:"English"},{name:"John",score:68,subject:"English"}]
],
// ...

我想在将相同的主题分组在一起时循环并打印:

<div *ngFor = "let test of tests;let i = index">
  <ul *ngFor = "let student of test[i] ;let n = index">
     <li>{{student.name+' '+student.score}}</li>
  </ul>
</div>

但最终会出现错误:

错误错误:找不到“对象”类型的不同支持对象[object Object]。 NgFor 只支持绑定到 Arrays 等 Iterables。

从第二个循环开始。请问我在这里错过了什么?

【问题讨论】:

  • 请提供有效的JSON
  • 使用 Object.keys()

标签: angular typescript multidimensional-array


【解决方案1】:

刚刚将test[i] 更改为test,这是一个数组,您可以对其进行迭代,但test[i] 是对象,不能进行迭代。

ts 代码:

 tests = [
          [{name:"Bob",score:40,subject:"Math"},{name:"John",score:55,subject:"Math"}],
          [{name:"Alice",score:70,subject:"English"},{name:"John",score:68,subject:"English"}]
        ]

html:

<div *ngFor = "let test of tests;let i = index">
    <ul *ngFor = "let student of test ;let n = index">
        <li>{{student.name+' '+student.score}}</li>
    </ul>
</div>

DEMO

【讨论】:

  • 感谢@Fateme,这非常方便。玛莎阿拉
  • 请说明您做了哪些更改,同样由ul 替换为div
【解决方案2】:

如果这是你的数组,你可以像这样循环它:

<div *ngFor="let test of tests">
  <ul *ngFor="let student of test">
     <li>{{student.name+' '+student.score}}</li>
  </ul>
</div>

【讨论】:

    【解决方案3】:

    我不是 Angular 开发人员,但尝试循环:

    let student of test[i] 更改为let student of tests[i]let student of test

    【讨论】:

      【解决方案4】:

      试试这个

       let tests = [
                    [{name:"Bob",score:40,subject:"Math"},{name:"John",score:55,subject:"Math"}],
                    [{name:"Alice",score:70,subject:"English"},{name:"John",score:68,subject:"English"}]
                  ];
      
      <div *ngFor="let test of tests">
          <ul *ngFor="let student of test">
             <li>{{student.name+' '+student.score}}</li>
          </ul>
        </div>
      

      【讨论】:

        猜你喜欢
        • 2021-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-29
        • 2022-05-12
        • 1970-01-01
        • 2021-01-11
        • 1970-01-01
        相关资源
        最近更新 更多