首页 > 解决方案 > 通过值数组 es6 过滤对象数组

问题描述

我需要帮助来执行一个函数来通过一个具有值的数组来过滤一个对象数组,例如:

我的对象数组:

const persons = [
  {
    personId: 1,
    name: 'Patrick',
    lastName: 'Smith',
    age: 27,
    allergy: [
    {
      idAllergy: 1,
      name: 'Fish'
    },{
      idAllergy: 2,
      name: 'Nuts'
    }
    ]
  },
  {
    personId: 2,
    name: 'Lara',
    lastName: 'Blake',
    age: 21,
    allergy: [
    {
      idAllergy: 2,
      name: 'Nuts'
    }
    ]
  },
  {
    personId: 3,
    name: 'Erick',
    lastName: 'Robinson',
    age: 30,
    allergy: [
    {
      idAllergy: 3,
      name: 'Flowers'
    }
    ]
  },
  {
    personId: 4,
    name: 'Hilda',
    lastName: 'Vianne',
    age: 35,
    allergy: [
    {
      idAllergy: 4,
      name: 'Chocolat'
    }
    ]
  }

]

我的数组要过滤的值:

// 这些是 idAllergy let allergy = [2,3]

所以计划是使用过敏数组值来寻找对坚果和鲜花过敏的人,不显示他们,所以我的预期结果是:

 [{
    personId: 4,
    name: 'Hilda',
    lastName: 'Vianne',
    age: 35,
    allergy: [
    {
      idAllergy: 4,
      name: 'Chocolat'
    }
    ]
  }]

提前致谢

标签: javascripttypescriptecmascript-6

解决方案


如果您希望患有 2 型和 3 型过敏症的人这样做:

let allergy = [2,3];
const personsWithAllergy = persons.filter(
   p => p.allergy.some(al => allergy.includes(al.idAllergy)));

const persons = [
    {
        personId: 1,
        name: 'Patrick',
        lastName: 'Smith',
        age: 27,
        allergy: [
            {
                idAllergy: 1,
                name: 'Fish'
            },{
                idAllergy: 2,
                name: 'Nuts'
            }
        ]
    },
    {
        personId: 2,
        name: 'Lara',
        lastName: 'Blake',
        age: 21,
        allergy: [
            {
                idAllergy: 2,
                name: 'Nuts'
            }
        ]
    },
    {
        personId: 3,
        name: 'Erick',
        lastName: 'Robinson',
        age: 30,
        allergy: [
            {
                idAllergy: 3,
                name: 'Flowers'
            }
        ]
    },
    {
        personId: 4,
        name: 'Hilda',
        lastName: 'Vianne',
        age: 35,
        allergy: [
            {
                idAllergy: 4,
                name: 'Chocolat'
            }
        ]
    }

]


const allergy = [2,3];
const personsWithAllergy = persons.filter(p => p.allergy.some(al => allergy.includes(al.idAllergy)));

console.log(personsWithAllergy);


推荐阅读