首页 > 解决方案 > 使用 Array.find() 在对象数组中查找对象

问题描述

所以我有一个名字数组:

const names = ['student1', 'student2', 'student3']

我有一系列出勤对象:

const attendance = [
  {student1: ['On Time', 'Late']},
  {student2: ['Late', 'Late']},
  {student3: ['On Time', 'Excused']},
]

我想根据名称数组中的名称在出勤数组中找到学生对象。

所以目前我有:

names.forEach(person => {
  function attendanceData(p) {
     return Object.keys(attendance).toString() == p.toString()
  }
  console.log(attendance.find(attendanceData(person)))
})

但是,这给了我一个错误说:

Uncaught (in promise) TypeError: false is not a function

下一个堆栈显示“在 Array.find()”

我想知道我怎么没有正确使用它,如果有更好的方法来做到这一点,我该怎么办?

标签: javascriptarrays

解决方案


我相信这就是你想要的。不过,您的数据结构有点奇怪,所以我想更广泛地了解您希望这段代码做什么。

const findStudentAttendance = (att, studentName) => {
  return att.find(obj => Object.keys(obj)[0] === studentName)
}

names.forEach(name => {
  console.log(
    findStudentAttendance(attendance, name)
  )
}) /* =>
{ student1: [ 'On Time', 'Late' ] }
{ student2: [ 'Late', 'Late' ] }
{ student3: [ 'On Time', 'Excused' ] }
*/

推荐阅读