根据几个键过滤数组

时间:2018-03-20 08:33:33

标签: angular typescript

我有一群人,他们有一些关于他们的信息。
我想根据宗教,性别和记录号同时过滤这个数组。
有办法吗?

这是 PEOPLE 数组:

{
    "Id": 1270,
    "FirstName": "name",
    "LastName": "last name",
    "Religion": "religion",
    "RecordNumber": 1,
    "Gender": "male",
    "Contacted": false,
    "NeedsTransportation": false,
    "WhenContacted": null,
    "ContactedByWho": null,
    },
     {
     "Id": 1383,
     "FirstName": "name",
     "LastName": "last name",
     "Religion": "religion",
     "RecordNumber": 1,
     "Gender": "male",
     "Contacted": false,
     "NeedsTransportation": false,
     "WhenContacted": null,
     "ContactedByWho": null
    },
    {
     "Id": 1394,
     "FirstName": "name",
     "LastName": "last name",
     "Religion": "religion",
     "RecordNumber": 1,
     "Gender": "male",
     "Contacted": false,
     "NeedsTransportation": false,
     "WhenContacted": null,
     "ContactedByWho": null,
    }

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

使用filter

const people: Person[] = [...];
people.filter(p => {
   return p.Religion === (...) // condition for religion
       && p.Gender === (...) // condition for gender
       && p.RecordNumber === (...); // condition for record number
});

当然,条件不一定是平等比较,也不必使用AND运算符。我们的想法是filter方法将返回一个新数组,该数组仅包含作为参数传递的函数返回true的那些项。在里面你可以做任何你需要的检查。

答案 1 :(得分:1)

为什么你不能filter

 var filteredResult =   x.filter((x)=> (x.Id == 1394) && (x.Religion =="religion") && (x.Gender=="male") )

当然,您可以使用任何运算符,它可以为您正在迭代的项目提供布尔值true,以便在结果数组中获取该项目

答案 2 :(得分:1)



let people = [{
    "Id": 1270,
    "FirstName": "name",
    "LastName": "last name",
    "Religion": "religion",
    "RecordNumber": 1,
    "Gender": "male",
    "Contacted": false,
    "NeedsTransportation": false,
    "WhenContacted": null,
    "ContactedByWho": null,
    },
     {
     "Id": 1383,
     "FirstName": "name",
     "LastName": "last name",
     "Religion": "religion",
     "RecordNumber": 1,
     "Gender": "male",
     "Contacted": false,
     "NeedsTransportation": false,
     "WhenContacted": null,
     "ContactedByWho": null
    },
    {
     "Id": 1394,
     "FirstName": "name",
     "LastName": "last name",
     "Religion": "christian",
     "RecordNumber": 1,
     "Gender": "male",
     "Contacted": false,
     "NeedsTransportation": false,
     "WhenContacted": null,
     "ContactedByWho": null,
    }]
    

const FILTER = (RELIGION, GENDER, RECORD_NUMBER) => {
  return people.filter(({Religion, Gender, RecordNumber}) => Religion === RELIGION && Gender === GENDER && +RecordNumber === +RECORD_NUMBER)
}
   
let filteredPeople = FILTER('christian', 'male', 1)
   
console.log(filteredPeople)




我在+参数之前添加RecordNumber && RECORD_NUMBER运算符,因为它作为字符串传递,例如+'1' === 1