有人能帮我想出一种更快的方法来过滤下面的ArrayC
吗(请参阅下面它应该等于什么。ArrayA
不言自明。ArrayB
在每个元素内部都有一个对象'data'
,它的属性"target"
是字符串"_teacher"
,我可以根据全局变量"userType"
过滤掉它,以区分学生和老师。"filter_klas_1371" ==> filter_{GroepType }_{GroepID}
来自数组a。此属性发生更改。打破字符串和过滤让我头疼,所以如果有更快、更有效的方法来过滤,请告诉我。
let userType='teacher'
arrayA: [{
"ID": 1,
"GroepID": 1371,
"GroepType": "klas"
},
{
"ID": 2,
"GroepID": 1372,
"GroepType": "klas"
},
{
"ID": 3,
"GroepID": 1375,
"GroepType": "graad"
}
]
araayB: [{
"id": "bd5b12ba-b433-4610-801e-e0b78fa72ff8",
data: {
"target": "_teacher",
"filter_klas_1371": "true"
}
},
{
"id": "gggfdgdba-gfgg-fff-ggg-7657657676",
data:{
"target": "_teacher_student",
"filter_klas_1375": "true"
}
} {
"id": "uuuykllk-b433-4610-801e-8888888776",
data: {
"target": "_student",
"filter_klas_1372": "true"
}
} {
"id": "jkjkjkklk-jkhjk-66567-666-99977",
data: {
"target": "_teacher_student",
"filter_klas_1372": "true"
}
},
{
"id": "zzzzzzz-b433-4610-801e-8888888776",
data: {
"target": "_teacher",
"filter_klas_1372": "true"
}
},
]
//should get
arrayC:[{
"id": "bd5b12ba-b433-4610-801e-e0b78fa72ff8",
data: {
"target": "_teacher",
"filter_klas_1371": "true"
}
},
{
data: {
"id": "jkjkjkklk-jkhjk-66567-666-99977",
"target": "_teacher_student",
"filter_klas_1372": "true"
}
},
{
"id": "zzzzzzz-b433-4610-801e-8888888776",
data: {
"target": "_teacher",
"filter_klas_1372": "true"
}
}
]
如果我理解正确,您希望根据userType和arrayA中的值筛选arrayB。我建议用阵列图制作一个所有可能的filter_{groepType}_{groepId}
的阵列:
const filterKeys = arrayA.map(group => `filter_${group.GroepType}_${group.GroepID}`);
然后,您可以使用数组与几个过滤器的交集来检查这些值中的一个是否设置为arrayB的键中的键。你可以用更多的方式做到这一点:
arrayC = arrayB.filter(item => {
const intersect = Object.keys(item.data).filter(key => filterKeys.includes(key));
return intersect.length > 0; // you can additionally add the filter for target here
})