L
L
Let_peace2020-08-04 14:04:23
JavaScript
Let_peace, 2020-08-04 14:04:23

How to fix “Cannot read property ' ' of undefined” error when working with JSON and JavaScript?

I work with JSON through a JavaScript script. JSON file:

{
  "section_1" : {
    "1_1" : {
      "name" : "№1",
      "description" : "",
      "image" : "images/1_1.jpg"
    },
    "1_2" : {
      "name" : "№2",
      "description" : "",
      "image" : "images/1_2.jpg"
    }
  },
  "section_2" : {
    "2_1" : {
      "name" : "№3",
      "description" : "",
      "image" : "images/2.jpg"
    }
  }
}

js file:
$.getJSON('./MyJSON.json', function (data) {
        var out = '';
        for (var section in data){ // вывод всех товаров
            for (var key in section){
                out+='<img src="'+data[section][key].image+'" alt="">';
                out+='<h5>'+data[section][key]['name']+'</h5>';
                if (data[section][key]['description'] != "") {
                    out+='<p>'+data[section][key]['description']+'</p>';
                }
            }  
        }
    });

When loading the page and accessing the values ​​of objects, the console gives the following error (screenshot is also attached): Cannot read property 'image' of undefined. Screen is attached.
5f2940a3a357f816804210.png
Tell me, please, what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-08-04
@Let_peace

for (var section in data) {
  for (var key in data[section]) {
    ...
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question