javascript - 通过值数组 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'
}
]
}]
提前致谢
解决方案
如果您希望患有 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);
推荐阅读
- unity3d - unity 3rd 人称控制器,旋转噩梦
- java - 如何在 java 中读取 JSON-LD?
- c++ - 在我自己的堆栈中实现顶部的问题
- pyspark - Dataproc:pyspark UDF 的 functools.partial 没有属性“__module__”错误
- java - 如何将带有用户名和密码的 Java mqtt 客户端连接到 emqttd(EMQ) 代理?
- objective-c - 如何排除类
-swift.h - image - 在 Golang 中绘制两个半径的圆
- javascript - 用于更改文本的敲除按钮单击绑定
- python - 如何根据 DataFrame 中元素的长度更改列值
- scala - 安全尝试清理