I’m working with a JavaScript object, and when I do console.log(sessions)
, it outputs the following structure on console:
{
101: { "id": 101, "nameEn": "English 1", "nameFr": "French 1" },
102: { "id": 102, "nameEn": "English 2", "nameFr": "French 2" },
103: { "id": 103, "nameEn": "English 3", "nameFr": "French 3" }
}
The sessions
data type is an object.
I’m trying to write a function that retrieves the nameEn
and nameFr
values based on a given id. Here’s what I’ve tried:
// Function to fetch nameEn and nameFr based on id
const getNameById = (id) => {
const session = sessions.find(session => session.id === id); // Line A
if (session) {
return { nameEn: session.nameEn, nameFr: session.nameFr };
} else {
return `No session found for id ${id}`;
}
};
// Example usage
console.log(getNameById(101));
console.log(getNameById(102));
console.log(getNameById(103));
However, at Line A, I’m encountering the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'find')
What am I missing, and how can I fix this to properly retrieve the nameEn
and nameFr
based on the id?