【问题标题】:Typescript/Angular 2 - filter out objects that do not include a specific string propertyTypescript/Angular 2 - 过滤掉不包含特定字符串属性的对象
【发布时间】:2018-11-05 18:52:10
【问题描述】:

我正在我的 Angular 应用程序中创建一个过滤器,用于删除嵌套数组中不包含特定字符串属性的所有对象。

例如...我有一个如下所示的数组:

JSON:

[
  {
    "id":1,
    "name":"example1",
    "categories": [
      "red",
      "yellow",
      "pink",
      "green"
    ]
  },
  {
    "id":2,
    "name":"example2",
    "categories": [
      "blue",
      "black",
      "purple",
      "green"
    ]
  },
  {
    "id":3,
    "name":"example3",
    "categories": [
      "red",
      "yellow",
      "black",
      "white"
    ]
  }
]

当您单击按钮时,该功能将仅显示包含指定类别的对象。

类似...

<button (click)="filter('red')">filter by category</button>

filter(category) {
  // only show objects that contain (category) string.
}

任何帮助都会很棒,因为我还没有设法破解它。

希望这是足够的信息

【问题讨论】:

  • 你知道数组有“过滤”方法吗?

标签: angular typescript filter


【解决方案1】:

您可以将 array.filterarray.includes! 一起使用

const data = [
  {
    "id":1,
    "name":"example1",
    "categories": [
      "red",
      "yellow",
      "pink",
      "green"
    ]
  },
  {
    "id":2,
    "name":"example2",
    "categories": [
      "blue",
      "black",
      "purple",
      "green"
    ]
  },
  {
    "id":3,
    "name":"example3",
    "categories": [
      "red",
      "yellow",
      "black",
      "white"
    ]
  }
];


const r = data.filter(d => !d.categories.includes('red'));
console.log(r);

所以你需要改变你的过滤功能,

filter(category) {
  const result = data.filter(d => !d.categories.includes(category));
}

【讨论】:

  • 谢谢萨吉塔兰。那么我的 filter() 函数会是什么样子呢?
  • 非常感谢。如果可行,将尝试并接受。
【解决方案2】:

使用filter 过滤掉您的记录。

组件

var arr = [
  {
    "id":1,
    "name":"example1",
    "categories": [
      "red",
      "yellow",
      "pink",
      "green"
    ]
  },
  {
    "id":2,
    "name":"example2",
    "categories": [
      "blue",
      "black",
      "purple",
      "green"
    ]
  },
  {
    "id":3,
    "name":"example3",
    "categories": [
      "red",
      "yellow",
      "black",
      "white"
    ]
  }
];


function filterData(colorName) {
    arr.filter((item) => {
      return item.categories.indexOf('white') !== -1;
    });
    console.log(arr);
}

HTML

<button (click)="filterData('red')"></button>

【讨论】:

    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2015-11-20
    相关资源
    最近更新 更多