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

Searching for paired values within an array using Javascript or Jquery

In my JavaScript code, I am working with an array called ppts that looks like: var ppts = []; //... ppts.push({x: mouse.x, y: mouse.y}); //... var tmpArr = []; for (var i=1;ppts.length-1; i++) tmpArr.push(ppts[i].x); alert(tmpArr[2]); tmp_ctx.lineTo(pars ...

Revamp your code by utilizing ES6 class to replace multiple if statements in Javascript

Currently, my code is filled with numerous if statements and I am considering a switch to classes in ES6. However, Javascript isn't my strong suit... so PLEASE HELP ME..! Previous code: //example code function first(){ console.log('first sce ...

Manage YouTube video played within html code

I am working on a page that contains a YouTube video embedded in HTML. I am trying to find a way to stop the video when it is closed using the YouTube API, but so far my attempts have been unsuccessful. I have included SWFObject and jQuery in the code, yet ...

Tips for updating NX webpack settings to enable dynamic imports within an Express application

As I utilize the NX package for my monorepo setup, I successfully created an Express app by following the provided commands. However, I am struggling with dynamic imports and unsure how to resolve this issue. My current bundler is webpack, which was precon ...

JavaScript - Removing an Array from an Object

Can an array be removed from an object? For instance, suppose I have an object named response with an array inside it called items: var response = { success: false, items:[] }; What is the method to remove 'items' from the response object? Tha ...

What is the process for obtaining the cypress interception fixture twice but in two distinct formats?

Hi there, I'm new to Cypress and facing a challenge that I hope you can help me with. In my test file, I have the following code: cy.SetupClassificationsStubFixture(1); This code refers to a custom command that I've created: Cypress.Commands.ad ...

Is it better to have JavaScript and HTML in separate files or combined into a single HTML file?

Do you notice any difference when coding in both HTML and JavaScript within a single .html file compared to separating HTML code in a .html file and JavaScript code in a .js file? Does the functionality remain the same in both scenarios? For example, in t ...

Start by declaring a scope variable using AngularJS

My go-to method for retrieving data from the server and displaying it on various components like tables or charts is by using ng-init="controllerFunction()". This function needs to be called every time the page loads. While ng-init gets the job done, I ca ...

The content within the iframe is not displayed

I've set up a dropdown menu with separate iframes for each option. Here's the code I used: $(function(){ $('#klanten-lijst').on('change',function(){ $('#klanten div').hide(); $('.klant-'+t ...

Top solution for efficiently capturing and storing user input in a React JS application: Event Handler

I've recently designed an input field for inputting details of items. In order to effectively capture and save the entered information, which of the following event handlers would be most suitable? onClick onChange onLoad onKeyPress ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

"A currency must be designated if there is a value present in a monetary field" - The default currency is established

I've encountered a major issue with one of my managed solutions. I have a customized workflow that generates multiple custom entities, each with various money fields. Here's the scenario when I trigger my workflow: The custom workflow enters a ...

Utilizing a npm module in a web browser following importing in Node.js

I recently installed an npm module, but I'm having trouble figuring out how to use it in the browser after importing it. First, I installed the npm module using the following command (using a dummy example module): npm install sample-module In my p ...

Is there a way to restrict access to my website to only be opened in the Chrome browser?

Is there a way to prevent my web application from loading when the link is opened in browsers other than Chrome? Can this be achieved using Javascript or Java? I want to restrict the usage of my web application to only Chrome. Any assistance would be appre ...

The websocket server implemented in Node.js with the use of the "ws" library is exhibiting a peculiar behavior where it disconnects clients at random intervals,

My WebSocket server implementation is quite simple: const WebSocket = require('ws'); const wss = new WebSocket.Server( { server: server, path: "/ws" }); wss.on('connection', function connection(ws, req) { console.log("Connect ...

Sort through various table columns

I am currently utilizing a data table component from Framework7, which is being generated dynamically with JSON data. My goal is to make the column filter input functional within the table. So far, I have succeeded in implementing the filter for the first ...

Tips for changing the size and color of SVG images in a NextJS application

Looking to customize the color and size of an svg image named "headset.svg". Prior to this, I used next/image: <Image src={'/headset.svg'} alt='logo' width={30} height={30} className='object-contain' /> The s ...

"Node.js hiccup: Struggling to upload several images at once

I encountered an issue while trying to upload images to mongo db using Postman, as it displays "img": null after clicking on send button. Utilizing Flutter for the frontend, I am working on creating a rest API. While successful in uploading a single image ...

Avoiding GulpJs freezing with effective error handling techniques

I am currently in the process of converting my sass files to css and encountering some issues. Specifically, I am struggling with handling errors during the sass conversion process. Whenever there is an error, it causes gulp to hang, requiring me to rest ...

Troubleshoot: Json causing issue with displaying markers on Google Maps API (v3)

I developed a custom Google Maps application using JSON data and implemented PostgreSQL database integration. Here is the code snippet: <script type="text/javascript"> var map; var national = [{"lng":"-6.173319","city":"JAKARTA","lat":"106.818 ...