So I have an array of names:
const names = ['student1', 'student2', 'student3']
and I have an array of attendance objects:
const attendance = [
{student1: ['On Time', 'Late']},
{student2: ['Late', 'Late']},
{student3: ['On Time', 'Excused']},
]
I wanted to find the student object in the attendance array based off the names from the names array.
So currently I have:
names.forEach(person => {
function attendanceData(p) {
return Object.keys(attendance).toString() == p.toString()
}
console.log(attendance.find(attendanceData(person)))
})
However, this gives me an error saying:
Uncaught (in promise) TypeError: false is not a function
The next stack says "at Array.find()"
I'm wondering how I'm not using this correctly and if there was a better way to do this, what should I do?
2 Answers 2
I believe this is what you want. Your data is structured a little strangely though, so I would like to know on a larger scale what you want this code to do.
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' ] }
*/
1 Comment
try it
let result = attendance.filter(obj => names.includes(Object.keys(obj)[0]))
console.log(result)
Use array's method "filter" for getting items. You need get keys of object and take first key. And then you'll can check presence in names array, via array's method "includes"
more information about this methods here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Filter
Object.keys(attendance).toString()will be"0,1,2"attendancewould be{name: 'student', attendance: [...]}. That way you don't need to guess at random keys