Typescript使用filter()过滤数组

时间:2018-11-23 14:17:11

标签: angular typescript

我在下面有约定列表,我想按专业过滤此列表,即当我输入15时,返回ID为1和2的约定

[
 {
   "id": 1,
   "typeActivities": [
      {
        "id"=11,
        "specialitiesId": [10, 15]
      }
   ]
 },
 {
   "id": 2,
   "typeActivities": [
      {
        "id"=22,
        "specialitiesId": [10]
      },
      {
        "id"=222,
        "specialitiesId": [15]
      }
   ]
 },
 {
   "id": 3,
   "typeActivities": [
      {
        "id"=33,
        "specialitiesId": [12]
      }
   ]
 }
]

我尝试使用此功能,但什么也没返回

let input: number = 15;
let convention: Convention[];
convention = this.conventions.filter(convention => {
    let typeActivities: TypeActivity[] = convention.typeActivities.filter(typeActivitiy => {
        if (typeActivitiy.specialitiesId) {
            return input == typeActivitiy.specialitiesId.find(id => id == input);
        }
    });
    //console.log(convention.typeActivities.map(i => i.id).filter(item => typeActivities.map(i => i.id).indexOf(item) >= 0));
});

1 个答案:

答案 0 :(得分:5)

Array#some对于这样的事情真的很有用:

let input: number = 15;
let convention: Convention[];
convention = this.conventions.filter(convention =>
    convention.typeActivities.some(activity =>
        activity.specialitiesId.some(e => e == input)
    )
);

convention.typeActivities.some(...)将对每个条目调用其谓词,直到用尽(some返回false)或谓词返回真实值(some返回{{1} });与true相同。

实时JavaScript示例:

activity.specialitiesId.some(...)
const example = {
    conventions: [
      {
          "id": 1,
          "typeActivities": [
              {
                 "id": 11,
                 "specialitiesId": [10, 15]
              }
          ]
      },
      {
          "id": 2,
          "typeActivities": [
              {
                  "id": 22,
                  "specialitiesId": [10]
              },
              {
                  "id": 222,
                  "specialitiesId": [15]
              }
          ]
      },
      {
          "id": 3,
          "typeActivities": [
               {
                   "id": 33,
                   "specialitiesId": [12]
               }
          ]
      }
    ],
    find(input) {
      let convention;
      convention = this.conventions.filter(convention =>
        convention.typeActivities.some(activity =>
          activity.specialitiesId.some(e => e == input)
        )
      );
      return convention;
    }
};
console.log(example.find(15));