【问题标题】:I can't iterate over object Object我无法迭代对象 Object
【发布时间】:2023-04-02 14:23:01
【问题描述】:

我得到了这样的嵌套 JSON

{"id":1,"category":"cat","iconUrl":"www.test.com","subCategoryEntity":[{"id":3,"subCategory":"sub3","products":[]},{"id":2,"subCategory":"sub2","products":[]},{"id":1,"subCategory":"sub1","products":[{"id":1,"fileDownloadUri":"http://localhost:8081/api/v1/downloadFile/paint-bucket-orange-2-300x300.jpg","productName":"Name","productPrice":20.0,"productDesc":"this is the discreption","productStock":15,"productImages":[]}]}]}

我需要遍历所有子类别并获取子类别中的所有产品

这是我的 Angular 代码

    <div *ngFor="let item of allProducts| keyvalue">
       {{item.key}}:{{item.value}}
   </div>

这是输出

【问题讨论】:

  • 你的 subCategoryEntity 是一个对象,这就是为什么你不能像以前的属性那样迭代它
  • 是否可以访问子类别中的元素?它显示在浏览器控制台中如果不是这个API需要再​​次重构吗?
  • 您能在此处添加您的期望值以及它应该如何代表您的值吗?
  • 我可以打印子类别和子类别中所有产品的期望值。
  • 我正在考虑使用界面,但我不知道这是否可行

标签: angular typescript ngfor


【解决方案1】:

要迭代所有子类别中的所有产品,您可以执行以下操作:

<div *ngFor="let subCategory of allProducts.subCategoryEntity">
   <div *ngFor="let product of subCategory.products">
      {{product.id}}-{{product.productName}}
   </div>   
</div>

我认为这是你想要的,它不是最好的方法。

我建议您遍历 'allProducts' 和 'subCategories' 并提取变量中的产品以仅执行一个 'ngFor'

【讨论】:

  • 不起作用我得到一个错误,不能迭代对象只能迭代数组
  • 对象'allProducts'是一个数组?
  • 我收到此错误“{} 类型上不存在属性 'subCategoryEntity'”
  • @JoséEduardoUrzedaFerreira 他问题的第一行包含该对象。你应该已经完整阅读了
  • @Alaaebeed 这很奇怪,因为在您的问题对象中有“subCategoryEntity”,请向我们展示 typescript 中的“allProducts”对象
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 2021-04-15
相关资源
最近更新 更多