javascript - 使用 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()”
我想知道我怎么没有正确使用它,如果有更好的方法来做到这一点,我该怎么办?
解决方案
我相信这就是你想要的。不过,您的数据结构有点奇怪,所以我想更广泛地了解您希望这段代码做什么。
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' ] }
*/
推荐阅读
- spring - Bootstrap 4 样式未使用带有 thymeleaf 的 spring boot 加载
- clang - 如何提取存储在 llvm.ident 中的信息?
- javascript - 检查数组中是否存在某些内容的最佳方法是什么?
- python - 如何在Python中将带有“”(而不是“)的JSON字符串转换为JSON
- cypress - 在 Bamboo CI 运行后,即使某些 Cypress 测试失败,它也表明构建作业成功
- symfony - 如何根据主机动态设置_locale
- php - Laravel/Algolia - `php artisan scout:import "App\item" ` 不更新 Algolia 中的属性
- powerbi - 无法在 Databricks 中查看数据框
- python - 点积和矩阵乘法的Tensorflow慢
- javascript - tslint:使用 reduce 构建对象时无对象突变