我有两个数组变量
let itSchool = [
{
'school': 'HS-1',
'teachers': [
{
'name': 'John'
},
{
'name': 'Eddy'
}
]
},
{
'school': 'HS-2',
'teachers': [
{
'name': 'Edward'
},
{
'name': 'John'
}
]
}
]
let itAbsence = [
{
'school': 'HS-1',
'teacher': 'John'
},
{
'school': 'HS-2',
'teacher': 'Edward'
}
]
如何删除同名的itSchool
by 比较itAbsence
?结果变成:
itSchool = [
{
'school': 'HS-1',
'teachers': [
{
'name': 'Eddy'
}
]
},
{
'school': 'HS-2',
'teachers': [
{
'name': 'John'
}
]
}
]
itAbsent.forEach( absent => {
let index = itSchool.findIndex( schoolVar => absent.school === schoolVar.school );
if( index === -1 ) return;
let teacherIndex = itSchool[index].teachers.findIndex( teacher => teacher.name === absent.teacher );
if(teacherIndex != -1) itSchool[index].teachers.splice(teacherIndex, 1);
}
所以,这是一个基本逻辑:
迭代 itAbsent
对于其中的每个对象,在 中找到匹配学校的索引itSchool
。
在该teachers
学校的数组中找到缺席教师的索引。
删除必要的老师array.splice()
。
请注意以下几点:
这仅在每所学校有一名缺席教师时才有效。如果有更多 - 它们必须位于itAbsent
数组中的不同对象上。
如果在 中找不到学校或缺席的老师itSchool
,则函数将不执行任何操作(只是跳过它)。
该splice
方法实际上改变了我们正在处理的相同数组,例如itSchool[index].teachers
在这种情况下。如果您不想更改它,则必须创建它的副本并将该副本传递给此代码以进行更改。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句