What is the best method for retrieving the character's ID from within an object?

Exploring my collection of movies, I discovered that each movie contains an array of characters. My goal is to display specific information about each character (such as their name and age) when clicked on, requiring me to obtain the id of each character.

const PopularBooks = [
  {
    id: 1,
    title: "Harry Potter",
    characters: [
      {
        id: 10,
        name: "Harry Potter",
      },
      {
        id: 11,
        name: "Hermione",
      },
      {
        id: 12,
        name: "Ron",
      },
    ],
  {
    id: 2,
    title: "Lord of the Rings",
    characters: [
      {
        id: 13,
        name: "Frodo",
      },
      {
        id: 14,
        name: "Legolas",
      },
      {
        id: 15,
        name: "Gandalf",
      },
    ],
  },
];

In the main book page, I have portraits of each character displayed as images. Clicking on a character leads to another webpage where the character's id is passed as a parameter.

        <% book.characters.forEach(character => { %>
          <div class="portrait">
            <a href="/character/<%= character.id %>">
              <img
                src="/images/characters/book-c-<%= character.id %>.png"
              />
            </a>
            <p><%= character.name %></p>
          </div>
          <% }); %>

Although I successfully set up the router function to handle characterIds, I encountered an issue when trying to compare the characterId with the actual id within the data array. This resulted in an error:

Cannot read properties of undefined (reading 'find')

const data = require("../data");

router.get("/character/:character", function (req, res, next) {
  const characterId = parseInt(req.params.character);
  const character = data.PopularBooks.characters.find(
    (characters) => characters.id === characterId
  );
  console.log(characterId);
  console.log(character);
  res.render("character", { character });
});

I am striving to create unique pages for each character, but I need guidance on resolving this error. What steps can I take to correct this issue?

Answer №1

To retrieve the characters array of a particular book, ensure that you are examining the correct book instead of searching through the entire collection of TrendingNovels. Start by identifying the accurate book using its unique ID before looking for the specific character:

...
//locate the book containing the character
const bookWithCharacter = data.TrendingNovels.find((novel) =>
  novel.characters.some((char) => char.id === characterId)
);

if (!bookWithCharacter) {
  //return an error message if the ID is not present in any book
  return res.status(404).send("Character not found");
}

//search for the exact character within the selected book
const character = bookWithCharacter.characters.find(
  (char) => char.id === characterId
);
....

Answer №2

The problem that arises is related to the way you are accessing characters in PopularBooks. Since each book contains its own set of characters and PopularBooks is an array of books, you need to search through the books to locate the correct character using its characterId. Your current approach, which involves directly accessing data.PopularBooks.characters, will not be successful because characters are specific to individual books within the PopularBooks collection.

 const data = require("../data");

router.get("/character/:character", function (req, res, next) {
  const characterId = parseInt(req.params.character);
  
  let foundCharacter = null;
  for (const book of data.PopularBooks) {
    foundCharacter = book.characters.find(character => character.id === characterId);
    if (foundCharacter) {
      break; 
    }
  }
  
  console.log(characterId);
  console.log(foundCharacter);
  
  res.render("character", { character: foundCharacter });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The error message "TypeError: Cannot read property 'map' of undefined when trying to set state as an array"

Encountering an error while trying to map the state for my posts:[] object: Error message: TypeError: this.state.posts.map is not a function While searching for a solution, I found something similar on this link, but unfortunately, it did not solve the ...

Using Javascript to Conceal Button for Unauthenticated Users

Our website is currently running on an outdated e-commerce CMS platform, which limits my options due to my beginner level skills in JavaScript and jQuery. One specific issue we are facing is the need to hide Prices and Add to Cart buttons for users who ar ...

Node.js - Retrieving user information upon login in the front-end

I've successfully built a couple of expressjs applications in the past, but I'm currently struggling to figure out how to pass the User Model to the front-end or include it in the req as a parameter. The app functions as a one-page web applicati ...

What methods can I use to stop the styles of a child component from impacting those of the parent component

Is there a way to create CSS rules that achieve the following conditions? The parent component's CSS does not impact the child component The child component's CSS does not affect the parent component The child component is sourced from an exte ...

Deactivate button using Javascript

Can anyone assist me with this issue I am having? I currently have a button set up as follows: <input type="button" id="myButton" name="myButton" value="ClickMe!!" onClick="callMe()"/> I need to disable the button using jQuery, standard javascript ...

Ensure that a specific value is maintained for a property of an element throughout its animation

There are two distinct types of components that I am working with, which I will refer to as .a and .b. It is possible that these components have been assigned certain CSS animations. I do not have the ability to control these keyframes, whether they are a ...

Change button to an ajax spinner when it is clicked using jQuery

$(".post-btn").html("<img src='../images/loader.gif' />"); Why isn't this code working? I know I have the correct selector because when I tried $(".post-btn").text('test'), it worked. I want the text of the button to change ...

How to utilize JavaScript to convert a string into a function name

In this specific scenario, I am required to trigger a function based on the data attributes associated with an HTML element. function func1(arg1){ alert("func1"); } function func2(arg2){ alert("func2"); } jQuery(document).on('click', & ...

Why do `resolutions` not receive support in package.json like they do in bower.json?

It's common knowledge that resolutions are utilized to address conflicts between packages in the bower.json file. I recently went through the package.json documentation, but couldn't locate any support for the resolutions feature. Could there be ...

Can JavaScript be used to dynamically update drop down lists in a gridview?

My gridview has multiple fields including PreviousPoints, GainedPoints, and TotalPoints. In edit mode, PreviousPoints is not editable, GainedPoints is a dropdown list, and TotalPoints is also a dropdown list. Whenever the selected value in GainedPoints ch ...

How to determine if an Angular list has finished rendering

I am facing an issue where I have a large array that is being loaded into a ul list using ng-repeat in Angular. The loading of the list takes too long and I want to display a loader while it's loading, but hide it only when the ul list is fully render ...

Issue with onClientClick not functioning properly when performing a jQuery function call

How can I make a jQuery form appear when an ASP.NET server-side button is clicked by the user? Currently, when I click on the button during runtime, the page reloads quickly without displaying the jQuery form. I am aiming to achieve a similar effect show ...

Is it possible to store dat.gui presets for controls that are dynamically added?

I have a dynamic dat.gui interface where I add controls, but the "save settings" feature doesn't seem to recognize them. var mygui = new dat.GUI(); mygui.remember(mygui); // Example of adding a control in the standard way mygui.control1 = 0.0; var c ...

Is it possible to invoke this JavaScript function like this?

Is there a way to call a function like item_edit.say hello by passing it as a string on the window object (similar to the last line in the snippet below)? var arc={ view: { item_edit: {} } }; arc.view.item_edit={ say_hello: function(){ alert(' ...

Step-by-step guide on showcasing a quiz utilizing Magnific-popup and ajax

My goal is to create a functionality that allows users to easily download and view a quiz in a lightbox with just one click. I have successfully set up the ajax features and believe I am using Magnific-popup correctly, but for some reason, the lightbox is ...

Leveraging a nodejs script integrated with socket.io within an angular/electron hybrid application

I have successfully created an electron/angular app that is functioning well. Additionally, I have developed a nodejs script to open a socket.io server using typescript + webpack to generate all files in a bundled js file. My challenge arises when trying ...

How come jQuery is retaining the original DOM element classes even after I have modified them using jQuery?

Here is the code snippet I am working on: $(".drop-down-arrow-open i").click(function(){ console.log("The click function for .drop-down-arrow-open is triggered even when it is closed"); let thisParent = $(this).closest(".projects-container").find(".need ...

`No valid form submission when radio buttons used in AngularJS`

Within my form, I have a single input text field that is required (ng-required="true") and a group of radio buttons (each with ng-model="House.window" and ng-required="!House.window"). Interestingly, I've discovered that if I select a radio button fir ...

The element.find() function is experiencing issues when utilizing a templateUrl within a directive

My aim is to apply focus on an input field using a custom directive within a form. Initially, everything was functioning correctly when utilizing the template property in the directive. However, upon transferring the template into a separate HTML file usin ...

Is it possible to use JavaScript to make a CSS animation mimic the behavior of a :hover effect?

My CSS animation looks like this: HTML: <div class="container" id="cont"> <div class="box show"></div> </div> CSS: .container { width: 100vw; height: 100vh; } .box { position: absolute ...