我有下面的约定列表,我想按专业筛选这个列表,即当我输入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));
});

最佳答案

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)或谓词返回truthy值(some返回true);与activity.specialitiesId.some(...)相同。
实时javascript示例:
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));

.as-console-wrapper {
  max-height: 100% !important;
}

关于angular - Typescript使用filter()过滤数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53448333/

10-12 13:07
查看更多