The JSON file is throwing an error: "Cannot access property 'x' of undefined at the second level."

Issue: Having trouble rendering the second level in the JSON file, as it gives an undefined error. Any assistance would be greatly appreciated.

HTML:

<div>
  <li data-item="item1">1<p></p><span></span></li>
  <li data-item="item2">2<p></p><span></span></li>
  <li data-item="item3">3<p></p><span></span></li>
  <li data-item="item4">4<p></p><span></span></li>

</div>

JS/JSON

var data = [
    {
        "word": "hello",
        "favnumber": "0070",
        "item": "item1",
        "color": "red"
   },
   {
        "word": "hello world",
        "favnumber": "0233070",
        "item": "item2",
        "color": "blue",
       "Promo": {
            "Price": 3.99
        }
   },
   {
        "word": "hello mom",
        "favnumber": "0070",
        "item": "item3",
        "color": "pink",
       "Promo": {
            "Price": 4.99
        }
   },
   {
        "word": "hello dad",
        "favnumber": "0070",
        "item": "item4",
        "color": "silver",
        "Promo": {
            "Price": 8.99
        }
   }    
];

var items = document.querySelectorAll('[data-item]');

for (var e in items) {
    var element = items[e];
    var name = $(element).attr('data-item');

    for (var i in data) {
        var item = data[i];

        if (name == item.item) {
            var colorValue = item.color;
            var promoPriceValue = item.Promo.Price; //this doesn't work//
            $(element).find('p').text(colorValue); //this works//
            $(element).find('span').text(promoPriceValue);
        }
    }
}

Example: http://jsfiddle.net/icovermaface/24L02a1q/1/

Answer №1

Aside from the fact that not all objects in your data variable have the same data structure, it would be beneficial to switch from using the for ... in pattern to iterating over a variable since you are looping through an array and not enumerating through a javascript object. Basically:

for(var e=0; e < items.length; e++)

and

for(var i=0; i < data.length; i++)

For more information on why avoiding the for ... in pattern with arrays is recommended, check out this link: Why is using "for...in" with array iteration a bad idea?

Answer №2

The initial element within your array does not contain a Promo field, resulting in an undefined error. It is important to check for the existence of the field before attempting to access it, or provide a default value.

Verification

if(item.Promo) {
    var promoPriceValue = item.Promo.Price
}

Default Value

var promoPriceValue = item.Promo ? item.Promo.Price : 10.99

You should also revise your loop structure to use a for-loop

(var i = 0; i < data.length; i++)
, as mentioned by Jason. The current structure is causing this error:

Uncaught TypeError: Cannot use 'in' operator to search for 'getAttribute' in 4

See the working fiddle here - https://jsfiddle.net/24L02a1q/7/

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

Is innerHTML incapable of executing JavaScript code?

Experimenting with a new technique where I divide my code into separate files to create multiple HTML pages instead of one large one. Using ajax to load them and then setting the content as innerHTML to a parent div results in clean code that works well in ...

Numerous Bourbon Refill Opportunities

I'm currently working on a project that involves using the Bourbon Refills UI elements and I have a particular query related to modals. Specifically, I need to have multiple modals open simultaneously in a certain scenario. Here's what I'm ...

Can anyone identify the result produced by this line of code? Utilizing the $.get method to access "http://192.168.4.1:80/" with the parameter {pin:p}

Can anyone explain the output of this line of code? $.get("http://192.168.4.1:80/", {pin:p}); I understand that it is an Ajax code that sends data through a GET request, but I am trying to manually send the same data like this ".../pin:13" or "", however ...

A guide to customizing the appearance of Textfield labels in Material-UI using React

Can someone assist me with changing the label color in Material-UI from grey to black? I am new to Material-UI and struggling to figure it out. Below is the code snippet: import React from "react"; import ReactDOM from "react-dom"; import { TextField, Bu ...

JSON file parser that outputs the schema of a JSON file

Is there a way to showcase the schema of a JSON file in a tree structure format? I am looking for a JSON parser in C++ that can generate the schema of a JSON file. ...

What is the method to apply a class exclusively to an img tag?

While using the Cycle2 Carousel plugin, I encountered an issue with the class being set for my thumbnails. The plugin sets the .cycle-pager-active class for both images and divs, which is not ideal. I attempted to fix this by adding 'img' before ...

Mastering the A-Frame Game Loop: Tips for Separating Logic and Rendering

Currently, I am experimenting with A-Frame and my Quest 2 headset in order to create a simple VR game. One particular challenge I am facing is understanding how to separate logic from rendering and establish a proper game loop. After discovering this tutor ...

Is there a way to delete specific information from a JSON response?

Received the service response in the following format: Temp([ { XXX: "2", YYY: "3", ZZZ: "4" }, { XXX: "5", YYY: "6", ZZZ: "7" }, { XXX: "1", YYY: "2", ZZZ: "3" } ]); I need to manipulate this response in J ...

Eliminate the Jquery Combobox

I've implemented the Jquery Combobox on my website /*! * Combobox Plugin for jQuery, version 0.5.0 * * Copyright 2012, Dell Sala * http://dellsala.com/ * https://github.com/dellsala/Combo-Box-jQuery-Plugin * Dual licensed under the MIT or GPL V ...

Extracting values from an event in Vue.js: A step-by-step guide

When working with Vue.js, I use the following code to fire an event: this.$emit("change", this.data); The parent component then receives this data, which is in the form of an object containing values and an observer. It looks like this: { data ...

What is the best way to selectively adjust object parameters in unit testing?

In my module, I have an object with several parameters. I want to rewire only specific parameters of this object. Here is a snippet from my 'module.js' file: var obj = { param_A: 'valueA', param_B: 'valueB', param_C: &a ...

Is there a way in Vue.js to create a description list (dl) using v-for?

The v-for directive in vue is truly remarkable. I am currently faced with a situation where I need to create a description list similar to this. To achieve this, I have to generate two DOM elements for each item in my array: <dl class="row"> < ...

Creating an interactive animation of bouncing balls within an HTML5 canvas using JavaScript

function refBalls(){ var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var circles = [{x:40,y:100,r:20,color:'black',vx:5,vy:10}] function draw(){ ctx.beginPath(); ctx.arc(circles[0].x, circles[0].y, circles[0].r, ...

Refresh all color pickers with Bootstrap 4 Colorpicker - enforce the update of every color selector

Currently, I am utilizing the Bootstrap 4 color picker library which can be found at this link: In my code, I have defined color pickers that look like this: <div class="input-group cpicker"> <input type="text" class="form-control input-lg" ...

Issues with Ajax Requests

The pending requests from the Post need to be completed. I was hoping to record the JSON body of the request that comes in. Everything works fine when using Postman, but for some reason the AJAX requests are not functioning properly. Code snippet for Node ...

Enhancing User Experience with AJAX and JSON in Servlet JSP Applications

I've been working on my school project for a while, but I'm having trouble with the login page. Every time I try to log in, I receive a PARSING ERROR message like this: Error Login AJAX For the login process, I am using a simple servlet that co ...

Guide to stripping HTTP headers from a REST API request using JavaScript

Hey there! I'm currently working on extracting a specific part of the response from the {}. This information is retrieved from the gemini public database, and my goal is to retrieve only the content within the curly braces and store it as a string in ...

Can I use a single component for all routes in NextJS?

Just starting out with NextJS and facing a simple problem: I'm wondering if it's possible to achieve the following setup using NextJS // with react-router-dom <Router> <> <Header /> <Switch> & ...

What are some best practices for implementing responsive design using CSS @media queries with makeStyles in React.js Material UI?

const useStyles = makeStyles(theme => ({ wrapper: { width: "300px" }, text: { width: "100%" }, button: { width: "100%", marginTop: theme.spacing(1) }, select: { width: "100%", marginTop: theme.spacing(1) } })); I ...

Convert HTML form input into a JSON file for safekeeping

<div class="email"> <section class="subscribe"> <div class="subscribe-pitch"> </div> <form action="#" method="post" class="subscribe-form" id="emails_form"> <input type="email" class="subscribe-input" placeholder="Enter ema ...