Why does it display 'Undefined' when I attempt to access an object in an array in Next.js?

I am currently working on a way to display sub Products related to the main product. I have attempted to extract the product code from the URL and then retrieve sub-products that correspond to the main product code.

 List of Products and Sub products
const data ={
 product:[
   {
   title:'Product1',
   slug:'001',
   category:'shirt',
   image:'./../../public/image1.jpg',
   },
   {
   title:'Product2',
   slug:'002',
   category:'shirt',
   image:'./../../public/image2.jpg',
   },
],
subProduct:[
   {
   title:'subProduct1',
   slug:'001',   
   image:'./../../public/image01.jpg',
   price:70
   },
   {
   title:'subProduct2',
   slug:'001',   
   image:'./../../public/image02.jpg',
   price:200
   },
   {
   title:'subProduct3',
   slug:'002',   
   image:'./../../public/image03.jpg',
   price:170
   },
   {
   title:'subProduct4',
   slug:'002',   
   image:'./../../public/image04.jpg',
   price:150
   },

],

}

  const  slug  = '001';  
  const product = data.product.find(x => x.slug === slug);
  const subProducts =  data.subProduct.filter(function(x) {
  return x.slug == slug;});
  
  
  console.log(subProducts.title)[enter image description here][1]

the issue is it shows Undefined when I try implement like {subProducts.title}

but when I console.log(subProducts) I get Array of subProducts that match with the slug of the Main Product

Answer №1

subProducts is an array of objects. It's important to note that when accessing the title attribute of each item in the array, you should reference the individual object like subProducts[i].title. Attempting to access subProducts.title directly will result in returning undefined, as an array does not have a title property. The title attribute belongs to the objects within the array.

In React (as part of Next.js), when rendering an array, consider using this approach:

const Component(props) => {
  const subproducts = [{title: 'Foo'}, {title: 'Baz'}]

  return (
    <div>
     {
      subproducts.map((subproduct) => (
        <div key={subproduct.title}>{subproduct.title}</div>
      ))
     }
    </div>
}

The key attribute is essential in React. For further information on keys in lists, check out this resource.

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

How to add a jQuery function to a Rails 3 if statement?

I followed a Rails 3 tutorial on creating a multi-step form which you can check out here. Additionally, I incorporated Stripe payment functionality in my app using another railscast found here. Within my application, the payment form is hidden using jQuer ...

Creating a sticky section with Tailwind CSS utility classes

I have a page in my Next.js web app, and I want to make the section highlighted in blue (wrapped in <aside> tag) sticky so that it stays in place while scrolling, with only the main section containing the chart scrolling. The code snippet below is f ...

How come my $scope variables are not resetting when attempting to refresh the data?

I just started working with Angular and encountered an issue while trying to implement a reload button. My webpage displays a table with data pulled from a Parse database. The table can be modified using various buttons, and after making changes, I want to ...

Implementing a Toggle Feature in React Components for Looping Elements

Hey everyone, I'm encountering a problem on my development site and could use some assistance. The issue I'm facing involves looping through a data file to create project cards with show more/show less functionality for displaying/hiding descript ...

AngularJS encounters failure during shared data service initialization

As a newcomer to AngularJS, I aim to develop an application in adherence to John Papa's AngularJS style guide. To familiarize myself with these best practices, I have opted for the HotTowel skeleton. My application requires consuming an HTTP API endp ...

What is the best way to create direct links to tabs using #anchors in JavaScript?

I am managing a website that includes info-tabs based on a template I found at this link. The tabs contain anchors like example.com/#convey, but unfortunately, direct links to specific tabs using #anchor do not work properly due to the tabs relying on Java ...

Can you explain the contrast between 'depict' and 'examine' when using Jest?

I am currently diving into the world of unit testing in Vue.js with Jest. One question that keeps popping up is when to use describe and when to use test ? TodoApp.vue Component : <template> <div> <h1>TodoApp Componenent</h1> ...

I am experiencing difficulties with using the Material-UI Select component in NextJS

I am currently utilizing Material UI Select with Next.js and encountering some persistent errors on the page that I can't seem to resolve. You can view the errors in the following screenshot: Here is the code snippet in question: import Select from & ...

block the UI when a certain amount of time has passed

When I click on a button, I implement the following code: $(document).ready(function () { $('.find').click(function () { $.blockUI({ message: '<table><tr><td><img src="images/pleas ...

Applying conditional statements to an array's parent elements during iterations in JavaScript

Here is my complete script for relevance. I am currently looping through an array from a JSON object and populating content into an HTML div based on the content's ID. The process works well, but I am facing an issue with the logic related to the par ...

Extract Information from a Website

Is there a way to extract data from another website using JavaScript and save it into a .TXT or possibly an XML file? If JavaScript is not the best solution, I am open to other suggestions. I am specifically interested in extracting the price and item na ...

Prop validation error: The property "title" must be a string with a value of **, but a number with a value of ** was provided

My Vue js code displays data from a JSON API in a modal. The issue is that the title should be dynamic, but it only works when clicked twice. On the first click, I get an error and the cancel button, which triggers the hidemodal() function, crashes. Can an ...

Expressing the assignment of arrays inside the req.body object to separate variables

I've been facing some challenges trying to get Express and body-parser to properly interpret the JSON object sent from the Angular side of my app. It seems like there might be an issue with how I'm assigning variables in my syntax. Despite trying ...

Ways to verify if a user is authenticated without relying on request.session

I am currently developing a web application using Express, Docker, and following a Three-layered architecture. In my app, I store user login information in a session and have blogposts as a key resource. To retrieve the blogpostId from the database in the ...

Are Java's arrayLists a hybrid of arrays and lists?

During a recent project for school, I had the opportunity to work with arrayLists in Java. This got me thinking - is an arrayList considered as just an array, a list, or perhaps both? ...

Create a list using ReactJS

I've been working on rendering a dynamic list in JSX, but I'm facing issues displaying the items. Below is my code snippet where I attempted to use useState const [orderList, setOrderList] = useState([]) and setOrderList(prev => [...prev, chil ...

What is preventing me from loading a JavaScript script using a regular working URL?

After inserting the following line into my HTML file: <script type="text/javascript" src="http://static.citygridmedia.com/ads/scripts/v2/loader.js"></script> (whether inside or outside the <head></head> tags), I am encountering a ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Tips for Choosing the Right Objects in Vue.js

I have the following code that combines all objects in a person and stores them in an array called Cash:[] this.cash = person.userinvoice.concat(person.usercashfloat) Inside person.usercashfloat, there is an element called validate which sometimes equals ...

Issue in CakePHP after modifying the directory of Index

I'm currently working on a project using CakePHP and have come across an issue. Our team developed an Ajax function that sends data to a PHP function responsible for adding a folder (known as "ordner" in German) to the database. Initially, everything ...