I am struggling to showcase the values of character names stored within an array

I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen.

const PopularBooks = [
  {
    id: 1,
    title: "Harry Potter",
    characters: [
      {
        id: 1,
        name: "Harry Potter",
      },
      {
        id: 2,
        name: "Hermione",
      },
      {
        id: 3,
        name: "Ron",
      },
    ],
  {
    id: 2,
    title: "Lord of the Rings",
    characters: [
      {
        id: 4,
        name: "Frodo",
      },
      {
        id: 5,
        name: "Legolas",
      },
      {
        id: 6,
        name: "Gandalf",
      },
    ],
  },
];

Although I can display everything properly, I am facing difficulty in displaying character names.

    <div class="description">
      <h1><%= book.title %></h1>
    </div>
  </div>
  <div class="data-m1">
    <h4>Characters</h4>
    <div class="characters">
      <% for (let i = 1; i < 4; i++) { %>
      <div class="portrait">
        <img class="book-c" src="/images/book-c-1.png" alt="book" />
        <p><%= book.characters[0].name %></p>
      </div>
      <% } %>
    </div>
  </div>

When I change

<p><%= book.characters[0].name %></p>
to dynamically display all names using [i], it gives me an error:
Cannot read properties of undefined (reading 'name')
. Any suggestions or better ways to handle this?

If you're curious about how I obtained the value of book, here is the method:

router.get("/books/:title", function (req, res, next) {
  const bookId = parseInt(req.params.title);
  const book = data.PopularBooks.find((book) => book.id === bookId);
  res.render("books", { book });
});

Answer №1

As pointed out in Mamun@'s response, there seems to be an off-by-one problem in your loop. Instead of simply fixing that, I recommend utilizing forEach for better code readability and maintenance.

This approach enhances the clarity of your code by allowing you to focus on the intended operation for each element without having to manage indexes explicitly:

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

Answer №2

Starting from a position of 0, array indexing is essential to keep in mind. During the final loop iteration, attempting to access book.characters[3].name leads to the search for name beginning at the fourth spot within the characters array, resulting in a return value of undefined.

Replace the code snippet:

 <% for (let i = 1; i < 4; i++) { %>

With:

 <% for (let i = 0; i < 3; i++) { %>

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 MUI Slide Transition experiences a malfunction when using multiple Slide components simultaneously

I'm having trouble getting the animations to work for each mui Slide when the button is clicked. It seems like they don't want to cooperate and work together. Oddly enough, if you disable one of the slides, the other one starts working fine, but ...

Error in React+Redux: Trying to access the "address" property of a null value is not permitted

I am new to using react and encountering an issue with my ecommerce app. The app runs smoothly until I log out and then log back in at the shipping address page, which triggers the following error: TypeError: Cannot read property 'address' of nu ...

Troubleshooting Angular 2: Instances of Classes Not Being Updated When Retrieving Parameters

I am facing an issue with the following code snippet: testFunction() { let params = <any>{}; if (this.searchTerm) { params.search = this.searchTerm; } // change the URL this.router.navigate(['job-search'], {q ...

Utilize two separate functions within the onchange event of a v-checkbox component in a Vue.js application

I am currently using Vue.js with Vuetify and Laravel. In one of my components, I have a dynamic datatable that fetches data from the database using axios. Within this datatable, there are v-checkboxes. Everything is functioning as expected, but now I want ...

Is there a way to hide a button on this virtual keyboard after it has been clicked?

After creating a virtual keyboard using HTML and CSS, I am looking to implement JavaScript code that will hide a button after it is clicked. Here is the code I have tried so far: function hideButton() { var button = document.getElementById("simple_butto ...

Utilize key-value pairs to reference variables when importing as a namespace

Is it feasible to utilize a string for performing a lookup on an imported namespace, or am I approaching this the wrong way? Consider a file named my_file.ts with contents similar to: export const MyThing: CustomType = { propertyOne: "name", ...

Jquery Plugin fails to generate dynamic elements effectively

I developed a masking jQuery script that dynamically adds elements to an existing input element. var link = $('<a title="show" role="link" href="#" class="masker-value">show</a>'); wrapper: function() { container = $(container) ...

Apply bold formatting to the HTML text only, leaving the EJS variable untouched beside it

Is there a way to format the text for "Guest signed up" and "Guests attended" in bold while keeping the values normal? Here is my current code: <li class="list-group-item">Guests signed up: <%= guestSignups %></li> < ...

A comprehensive guide on properly obtaining user details in React with Redux and OIDC

Although I've dabbled in OIDC before, I wouldn't consider myself an expert. Currently, I'm trying to integrate OIDC into a react app using oidc-client-js and redux-oidc libraries, following the redux-oidc-example as a guide. Encountering th ...

Ways to prevent Express.js route from advancing to next()?

I encountered a strange scenario... In my web app, I am utilizing Express.js, Node.js, and Mongoose. Within one of the routes, there is a mongoose callback that triggers respond.send(...). However, as there are no further actions after the callback, it s ...

When integrating AngularJS $http with WordPress, the desired response may not always be achieved

I recently implemented a wp_localize_script for ajax in my WordPress project: wp_localize_script('cb_admin_js', 'cbAjax', array('ajax_url' => admin_url( 'admin-ajax.php' ))); As part of testing, I used an $http. ...

Developing a standard jQuery function for adding event listeners

Attempting to replicate the functionality of Google Maps' addListener using jQuery listeners for clicks, keypresses, etc. In Moogle Maps, you can use .event.addListener(map, 'click', function()... or switch 'click' with 'drag ...

Dealing with GraphQL mutation errors without relying on the Apollo onError() function

When managing access to an API call server-side, I am throwing a 403 Forbidden error. While trying to catch the GraphQL error for a mutation, I experimented with various methods. (Method #1 successfully catches errors for useQuery()) const [m, { error }] ...

Filtering database records using a static dropdown list in MVC 5: A step-by-step guide

Is there a way to filter database records based on the columns QtyRecieved, QtyRecievedand Void using a static HTML dropdown list? The QtyRecieved and QtyRecievedand column are both decimal values, while Void is a boolean. This is what I have attempted: ...

Exploring the dynamic duo of Django and DataTables: a guide on incorporating

Have you cautiously attempted to fetch data using AJAX, and displaying it in a datatable works seamlessly, but the issue arises when attempting to search or sort within the table. It seems that upon doing so, the data is lost, necessitating a page reload. ...

Is it possible for the NextJS Client component to only receive props after rendering props.children?

Encountering a puzzling issue that has me stumped... In my setup, I have a server side component that fetches data and then sends it over to the client component, which is all pretty standard. Here's where things get weird... When I log the data on ...

Accessing information from Firebase and displaying it within an Angular Controller

As a newcomer to the latest Firebase SDK (with some experience using angularfire), I set out to retrieve data and display it using Angular. This is my progress so far: var app = angular.module('dApp',[]); app.controller('listingControler&a ...

Guide to creating intricate designs on an HTML5 Canvas, one pixel at a time

Imagine a scenario where there is a 900x900 HTML5 Canvas element involved. In this case, there is a function named computeRow, which takes the row number as a parameter and returns an array of 900 numbers. These numbers represent colors ranging from 0 to ...

Could the absence of a tree view in the div be due to an error in the positioning of the DOM

I'm currently working on displaying a tree structure with specific child elements inside a div using JavaScript and HTML. Despite creating all the necessary objects and ensuring that the data is correctly read from the JSON file (refer to the "data" i ...

Decoding JSON using JavaScript

I am dealing with a webservice that uses RestEasy to return a JSON object with a List element. When I try to parse the results in a JavaScript loop, everything works fine if there are two or more elements in the List. However, if there is only one element, ...