Javascript 如何根据studCode id更改学生id
如何根据studCode更改学生的Javascript 如何根据studCode id更改学生id,javascript,typescript,Javascript,Typescript,如何根据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’
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_STUDENT',
姓名:“爱德华”
}, {
id:‘stud2’,
角色:'role_ADMIN',
名字:“杰克”
}]
常数studCode=[{
id:'1',
代码:“stud1”,
}, {
id:'2',
代码:'stud2',
}, {
id:'3',
代码:'stud3',
}]
const\u TEST=student.map(x=>{
返回studCode.filter(y=>y.code==x.id).map(z=>{
返回{…x,
id:x.id
}
})
})
console.log(_TEST)
您可以从.map更改为:
const student=[{
id:‘stud1’,
角色:'role_STUDENT',
姓名:“爱德华”
}, {
id:‘stud2’,
角色:'role_ADMIN',
名字:“杰克”
}]
常数studCode=[{
id:'1',
代码:“stud1”,
}, {
id:'2',
代码:'stud2',
}, {
id:'3',
代码:'stud3',
}]
const_TEST=student.flatMap(x=>{
返回studCode.filter(y=>y.code==x.id).map(z=>{
返回{…x,
id:x.id
}
})
})
console.log(_测试)
或者也
const _TEST = student.map(x => {
const studCodeMatch = studCode.filter(y => y.code === x.id)[0]
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
}
})