如何根据studCode id更改学生id

时间:2021-03-29 06:10:59

标签: 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',
  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)

2 个答案:

答案 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
    }
 })