1

I am not able to retrieve the values from an array after storing it in a variable outside of getJSON.

My JSON response is:

[
    {
        "Book_ID": "1",
        "Book_Name": "Computer Architecture",
        "Category": "Computers",
        "Price": "125.60"
    },
    {
        "Book_ID": "2",
        "Book_Name": "Asp.Net 4 Blue Book",
        "Category": "Programming",
        "Price": "56.00"
    },
    {
        "Book_ID": "3",
        "Book_Name": "Popular Science",
        "Category": "Science",
        "Price": "210.40"
    }
]

Using the jQuery $.getJson function:

  var booksList = [];
  $.getJSON( "books.json", function( data ) {
    $.each(data, function (index, value) {
     booksList.push(value);
    });
  });

When I try to get the BOOK ID,

console.log(booksList[0].BOOK_ID);

I get the following error:

Uncaught TypeError: Cannot read property 'Book_ID' of undefined

But when I log the complete array,

console.log(booksList);

I see this response in the console:

Zobia Kanwal
  • 4,085
  • 4
  • 15
  • 38

1 Answers1

0
var booksList = [];
$.getJSON( "books.json", function( data ) {
  $.each(data, function (index, value) {
   booksList.push(value);
  });
});

$.getJSON() returns immediately and $.each() also returns immediately, while the code inside the function is still executing in a separate thread. The code after that executes immediately and so the list isnt updated when you try to get data from it and its empty thus there is an error

var booksList = [];
$.getJSON( "books.json", function( data ) {
  $.each(data, function (index, value) {
   booksList.push(value);
   console.log(booksList[0].Book_ID);
  });
});
console.log("hi");

will show the updated list while "hi" gets printed first.

TheRealOrange
  • 115
  • 1
  • 1
  • 9