javascript - 如何显示对象数组中的特定对象(Angular 5、TypeScript)

标签 javascript html arrays angular typescript

我在 Angular 5 中有一个数据提供程序。

export class DataProvider {
  location: any;

  private locations: any[] = [
    {
      "name": "restaurant",
      "location": "downtown",
      "category": "restaurant",
      "id": "1"
    },

    {
      "name": "law firm",
      "location": "center city",
      "category": "office",
      "id": "2"
    },

    {
      "name": "public library",
      "location": "suburb",
      "category": "library",
      "id": "3"
    } ]

这是我的 HTML 文件。

<div *ngFor="let location of locations">
   <h1></h1>
    <h2></h2>
</div>

在这种情况下,如何加载具有某些属性的数据数组中的特定对象(项目)? 例如,如果我想加载带有 "category":"restaurant" 的对象,我应该对 HTML 文件做什么?所以另外两个人不应该出现。我只想使用此特定属性加载三分之一。

谢谢。

最佳答案

您需要访问该属性。您可以使用以下示例

<div *ngFor="let location of locations">
   <h1>{{location.name}}</h1>
    <h2>{{location.category}}</h2>
</div>

编辑

根据类别进行过滤:

locationsFiltered = this.locations.filter(location =>location.category=="restaurant");

现在为了使这个示例更加实用,我将创建一个方法来实现它

filter(category : string) : any[] {
   return this.locations.filter(location =>location.category==category);
}

然后在html中

<div *ngFor="let location of locationsFiltered">
   <h1>{{location.name}}</h1>
    <h2>{{location.category}}</h2>
</div>

关于javascript - 如何显示对象数组中的特定对象(Angular 5、TypeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49823736/

相关文章:

java - 仅显示最近添加的对象的数组列表

javascript - jQuery - 在 HTML PRE 中过滤 JSON 数组

javascript - 如何在 View 模型内容更新上调用 Jquery 函数

javascript - 响应式页脚和谷歌地图

Javascript 从文本文件中读取

javascript - Prop 在控制台中工作,但不在前端渲染 - React

html - 如何在调整浏览器窗口大小时使导航栏保持在其原始位置?

ios - 返回数组的快速函数