我有两个数组变量
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
进行比较来删除相同名称的itAbsence
?结果变为:
itSchool = [
{
'school': 'HS-1',
'teachers': [
{
'name': 'Eddy'
}
]
},
{
'school': 'HS-2',
'teachers': [
{
'name': 'John'
}
]
}
]
答案 0 :(得分:2)
一线解决方案
const itSchool = [
{
"school": "HS-1",
"teachers": [
{
"name": "John"
},
{
"name": "Eddy"
}
]
},
{
"school": "HS-2",
"teachers": [
{
"name": "Edward"
},
{
"name": "John"
}
]
}
]
const itAbsence = [
{
"school": "HS-1",
"teachers": "John"
},
{
"school": "HS-2",
"teachers": "Edward"
}
]
const output = itSchool.map(s => ({...s, teachers: s.teachers.filter(ss => ss.name !== (itAbsence.find(i => i.school === s.school).teachers)) }))
console.log(output)
答案 1 :(得分:0)
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
。如果您不想更改它,则必须创建它的副本并将该副本传递给此代码以进行更改。
答案 2 :(得分:0)
我已经解决了
let newSchool = itSchool
itAbsence.map(rA => {
itSchool.map(rS => {
for (const [k, v] of rS.teachers.entries()) {
if (v.name == rA.teacher) {
rS.teachers.shift()
}
}
return rS
})
newSchool = itSchool
})
console.log('itSchool = ', itSchool)