简体   繁体   中英

Cannot read property 'x' of undefined. second level in json file

Problem : Can not render second level in the JSON file for some reason but first level works. Second level is giving me undefined error. Please help.

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/

In addition to not all your objects in data having the exact same data-structure, I would change your for loops from the for ... in pattern to an iterated variable since you are iterating over an array and not enumerating over a javascript object. In other words:

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

and

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

Here is some more info on why not to use the for ... in pattern with arrays: Why is using "for...in" with array iteration a bad idea?

The first item in your array doesnt have a Promo field. This is throwing the undefined error. Do a check to see if the field exists before trying to access it or create a default value

check

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

default

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

Also you should change your loop structure, to a for (var i = 0; i < data.length; i++) as Jason mentioned. As structured they throw this error:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM