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

Resolve feature for UI routes fails to function upon refreshing the page

My app utilizes UI Route for view routing. When accessing /berlinerliste/, a function is triggered to display an array of objects. If one of these objects is clicked, the view changes to /berlinerliste/{id}/ and shows the details of that specific object. ...

Transform JSON data into an HTML layout

I'm looking to design a structure that showcases JSON information using HTML div elements. For example, utilizing the h4 tag for headers, p tag for text descriptions, and img tag for images. Can anyone provide guidance on the most efficient approach ...

In need of a collection of modules determined by a DefinePlugin constant

Currently, I am in the process of constructing a web application utilizing Webpack. However, I have encountered a challenge with a particular aspect of the design - hopefully someone in this forum has experience in similar tasks (or possesses enough knowle ...

Eliminate any line breaks from the information retrieved from the node event process.stdin.on("data") function

I've been struggling to find a solution to this issue. No matter what approach I take, I can't seem to remove the new line character at the end of my string. Take a look at my code below. I attempted using str.replace() in an effort to eliminate ...

Attempting to simulate the behavior of nfcManager by utilizing the nfcManager.start() function in react native testing library

In the process of developing my Android app, I encountered a need to read NFC tags. To accomplish this task, I decided to utilize the react-native-nfc-manager library. However, during my implementation, I faced two perplexing issues that have left me stump ...

`How can I integrate jQuery UI using Webpack in my project?`

I recently initiated a fresh project utilizing React Slingshot and am experimenting with integrating jQuery UI accordions. I've included the jQuery UI plugin using NPM with the command npm install --save jquery-ui. From what I comprehend, Webpack auto ...

Rendering basic JSON data from the console to an HTML page using Angular

I have been utilizing openhab for sensor monitoring. To extract/inject the items(things), sensor properties, and room configuration through a web interface, I am making use of openhab's REST queries which can be found here - REST Docs. Wanting to cre ...

Height Setting for Angular Material Buttons

html: <body id="app"> <md-button> Yo </md-button> </body> Looks: Why is the button set to 100% height? It should look like an inline element according to the materials documentation here. Also, why aren't the materi ...

manipulating dropdown visibility with javascript

I'm feeling a bit lost on how to structure this code. Here's what I need: I have 5 dropdown boxes, with the first one being constant and the rest hidden initially. Depending on the option chosen in the first dropdown, I want to display the corres ...

Is there a way to dynamically adjust the height of a DIV block?

I have a situation where I need the height of one div to automatically adjust based on changes in the height of another div. var height = jQuery('#leftcol').height(); height += 20; jQuery('.rightcol-botbg').height(height); Unfortun ...

Choosing a specific page number - kendo grid

Currently, I am working on creating a grid using kendo-telrik. Let's say I have 100 data items, but in the JSON format, I only have 10 data items (assuming each page contains 10 data items for pagination). However, I want to display all the pages (10 ...

Enhance a Javascript object by dynamically introducing new elements

I am currently working on a webpage using HTML and jQuery. My goal is to create a form where users can enter an email address in a textbox, and when they click a button, the email should be added to an object that displays all the emails entered so far. Th ...

Transforming an Axios image stream into a string by encoding it with Base64?

Currently, this is what I have in place: const Fs = require('fs') const Path = require('path') const Axios = require('axios') var {Base64Encode} = require('base64-stream'); const url = 'https://unsplash.co ...

Tips for sharing content within an iframe

Despite my efforts to find a solution, I have been unable to come across one that aligns with my specific situation. I currently have a form for inputting person data. Within this form, there is an iframe containing another form for adding relatives' ...

Error in Javascript chrome when trying to determine the length of an array

I am facing an unusual issue with the JavaScript console in Chrome. When I type the following code into the console: var numbers = new Array(["/php/.svn/tmp", "/php/.svn/props"]); it returns "undefined." This leads me to believe that 'numbers' ...

Remove the ability to select from the dropped list item

Here is the HTML and Javascript code I used to enable drag and drop functionality for list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop list in Green Area: </h4> <ul class="unstyle"> & ...

The second JSP page fails to load following an AJAX POST request

The following code snippet is found in page1.jsp. $.ajax({ type: "post", url: "page2.jsp", data: newdata, success:function(msg){ return msg; } ...

Definitions for images in the following format

I am currently utilizing typescript in conjunction with NextJs and next-images. Here is the code snippet: import css from "./style.sass"; import img from './logo.svg'; import Link from 'next/link'; export default () => <Link hre ...

Utilize PHP's file_get_contents to trigger the Google Analytics tracking pixel

For certain goals I have set up in Google Analytics, I am unable to use the JavaScript tracking. Instead, I am interested in achieving the same result by making a call with PHP. One solution that seems straightforward to me is to invoke the URL of the tra ...

The Ionic search bar will only initiate a search once the keyboard is no longer in view

In my Ionic application, I have implemented a search bar to filter and search through a list. The filtering process is triggered as soon as I start typing in the search bar. However, the updated results are not displayed on the screen until I manually hide ...