skip to Main Content

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?

2

Answers


  1. The find method doesn’t exist in sessions object, you need to use the Object class and pass the sessions as argument in values method for you to use find method.

    const getNameById = (id) => {
      const session = Object.values(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}`;
      }
    };
    
    Login or Signup to reply.
  2. Object.entries(obj).find(([key]) => key === keyToFind)
    const [key, value] = foundEntry
    

    use Object.entries to facilitate the iteration as if the object was and array

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search