Typescript / Angular 2-筛选出不包含特定字符串属性的对象

时间:2018-11-05 10:36:58

标签: angular typescript filter

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

例如...我有一个看起来像这样的数组:

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.
}

任何帮助都是很棒的选择,我只是没有设法破解。

希望这是足够的信息

2 个答案:

答案 0 :(得分:1)

您可以将 array.filter array.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));
}

答案 1 :(得分:0)

使用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>