如何根据另一个数组中的值过滤typesrcript中的对象列表

时间:2018-04-18 12:35:28

标签: typescript

在TypeScript中我有一个对象数组如下:

 let userTestStatus: { id: number, name: string }[] = [
  { "id": 0, "name": "Available" },
  { "id": 1, "name": "Ready" },
  { "id": 2, "name": "Started" },
  { "id": 3, "name": "UnKnown" }
];

我有另一个如下所示的数组,这是用户从选择框中多选的结果:

selectedValues=[1,3]

我需要过滤userTestStatus

中id 1,3

我的结果对象如下:

filteredUserTestStatus: { id: number, name: string }[] = [    
  { "id": 1, "name": "Ready" }      
  { "id": 3, "name": "UnKnown" }
];

我尝试过类似的事情:

userTestStatus.filter(x=>x.id.) but not sure how it will be done

1 个答案:

答案 0 :(得分:3)

您可以使用includes方法:



// Removed type so it can in browser on stackoverlflow , makes not difference.
let userTestStatus = [ 
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" },
    { "id": 3, "name": "UnKnown" }
];
let selectedValues = [1, 3]
let result = userTestStatus.filter(x => selectedValues.includes(x.id));
console.log(result);