Steven Steven - 5 months ago 68
jQuery Question

Using JSON file in HTML: Uncaught TypeError: data.forEach is not a function

I've browsed the web/docs and cannot find out why this is not working.

I am trying to insert data (quotes) from a JSON file:
{

"quotesArray":[{
"personName": "Albert Einstein",
"quote": "Look deep into nature, and then you will understand everything better."
},
{
"personName": "Stephen Hawking",
"quote": "Look deep into nature, and then you will understand everything better."
},
{
"personName": "Confucius",
"quote": "Life is really simple, but we insist on making it complicated."
}]}


Into a simple HTML div using the following JS:

$(document).ready(function() {
$("#realquote").on("click", function() {
$.getJSON('/json/quotes.json', function(data) {
var html = " ";
data.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'text-output'>";
keys.forEach(function(key){
html += val[key];

});
html += "</div>"
});


$(".realquote").html(html);
});
});
});


But every time, I get the error :TypeError: data.forEach is not a function" and I cannot figure out why.

If anyone could push me in the right direction, it would be greatly appreciated!

Answer

The data is a regular object that doesn't have .forEach method. You should iterate through the quotesArray property of the object.

data.quotesArray.forEach(fn);