如何根据studCode更改学生的id
。
预期输出:
student = [{
id: '1',
role: 'ROLE_STUDENT',
name: 'edward'
},{
id: '2',
role: 'ROLE_ADMIN',
name: 'jake'
}]
我试过是这样的,但它返回 [Array[1],Array[1]] 而是[对象,对象]
const student = [{
id: 'stud1',
role: 'ROLE_STUDENT',
name: 'edward'
}, {
id: 'stud2',
role: 'ROLE_ADMIN',
name: 'jake'
}]
const studCode = [{
id: '1',
code: 'stud1',
}, {
id: '2',
code: 'stud2',
}, {
id: '3',
code: 'stud3',
}]
const _TEST = student.map(x => {
return studCode.filter(y => y.code === x.id).map(z => {
return { ...x,
id: x.id
}
})
})
console.log(_TEST)
答案 0 :(得分:1)
您可以从 .map 更改为 .flatMap:
const student = [{
id: 'stud1',
role: 'ROLE_STUDENT',
name: 'edward'
}, {
id: 'stud2',
role: 'ROLE_ADMIN',
name: 'jake'
}]
const studCode = [{
id: '1',
code: 'stud1',
}, {
id: '2',
code: 'stud2',
}, {
id: '3',
code: 'stud3',
}]
const _TEST = student.flatMap(x => {
return studCode.filter(y => y.code === x.id).map(z => {
return { ...x,
id: x.id
}
})
})
console.log(_TEST)
答案 1 :(得分:0)
const _TEST = student.map(x => {
const studCodeMatch = studCode.find(y => y.code === x.id)
return {
...x,
id: studCodeMatch ? studCodeMatch.id : x.id
}
})
或者也
const _TEST = student.map(x => {
const studCodeMatch = studCode.filter(y => y.code === x.id)[0]
return {
...x,
id: studCodeMatch? studCodeMatch.id : x.id
}
})