From the server comes json in this form:

{ data: [ { "id": "7", "name": "Современные вызовы", "author": "Олег Калюжин", "theme": "Медицинская", "publisher": "Медицинское информационное агентство", "year": "2002", "count_page": "340", "price": "1200", "img": "7.jpg" }, { "id":"6", "name": "Психологические рисуночные тесты", "author": "Вася Пупкин", "theme": "Книги для родителей", "publisher": "АСТ", "year": "2013", "count_page": "176", "price": "890", "img": "6.jpg" } ] } 

when retrieving data, I try to create an array of objects myself,

 var x = new XMLHttpRequest(); ... var obj = eval(x.responseText); 

When I output the type obj - alert(typeof obj) , it displays the type object .

Now I want to work with this array of objects, for example, I need to display the name of the first element.

Cause it is (not sure what is right):

 alert(obj.data[0].name); 

The trouble ... The trouble does not display anything, alert(typeof obj.data[0].name) => undefined

In the browser's error console, the output is Uncaught TypeError: Cannot read property '0' of undefined

    1 answer 1

    Your faithful assistant is console.log:

     var obj = eval(x.responseText); console.log(obj); 

    and JSON.parse

     var obj = JSON.parse(x.responseText); 

    in the case of using eval, it’s not “parsing a string into an object”, but “applying a line of code”, which algorithm happens in this case — I’m not going to say for sure, but I assume that all properties of the object will turn into window properties. At the same time, eval is exactly to apply a line of code, its very use in this form is incorrect (it would be correct to have obj = json string ), and I now refuse to “use” a simple object.