首页 > 解决方案 > 角循环json显示数据

问题描述

我想创建一个循环来显示来自我的 json 的数据,但我不知道该怎么做,我是一个初学者,我想知道最好的方法。

问题是如何在知道有不同名称的键的情况下显示值“名称”?

提前致谢。

示例 json

{
  emptyKey: [],
  mdnCars:
  [
   {
     id: "1254",
     name: "tesla"
   }
  ],
  mdiBrand : [],
  mdnBrand:
  [
   {
     id: "1254",
     name: "renault"
   }
  ]
}

ts.文件

  getAll() {
    this.typeService.getAllType().subscribe(result => {
      this.array = result
    });
  }

标签: javascriptangulartypescript

解决方案


你有一个典型的问题,我可能有一个干净和适当的解决方案。

现在,如果您想*ngFor在 Angular 2+ 或ng-repeatAngular 中使用,最好的方法是根据您的需要操作数据。

考虑到你的json,

{
  emptyKey: [],
  mdnCars:
  [
   {
     id: "1254",
     name: "tesla"
   }
  ],
  mdiBrand : [],
  mdnBrand:
  [
   {
     id: "1254",
     name: "renault"
   }
  ]
}

您只想显示 JSON 中的名称,编写一个辅助函数,它可以返回类似这样的内容

[
  {
    id: "1254",
    name: "tesla"
  },
  {
    id: "1254",
    name: "renault"
  }
]

获得上述信息后,也许您可​​以根据需要直接使用 Angular 的指令。

我会写一个辅助函数,但不确定你的 JSON。如果您需要,请告诉我。

快乐编码:)


推荐阅读