Search code examples
javascriptjsonforeachaddeventlistenerstringify

Uncaught TypeError: json.forEach is not a function


let myJSON = { "name": "naam", 
    "schools" : [
        "silver stone"  , 
        "woodlands stone"  , 
        "patthar"
    ],
    "class" : 12 }

myJSON = JSON.stringify(myJSON) ; 
let json = JSON.parse(myJSON) ; 

json.forEach(e => {
     console.log(e.schools) ; 
});

I want to populate the school names on the page but not sure why I am getting this error:

" Uncaught TypeError: json.forEach is not a function "

can anyone help me resolve this?


Solution

  • forEach only works on array-type data.

    let myJSON = {
    "name": "naam" , 
    "schools" : [
         "silver stone"  , 
         "woodlands stone"  , 
         "patthar"
    ], 
    "class" : 12}
    
    let info = document.getElementById("info"); 
    let clickme = document.getElementById("clickme");
     
    myJSON = JSON.stringify(myJSON) ;
    /* "json" variable has a object type data */
    let json = JSON.parse(myJSON) ; 
    
    // For Each function only works on arrays.
    //you can't use it to loop directly on an object
    json.schools.forEach(e => {
         console.log(e) ; 
    });
    

    so to loop in the school array which is located at the json.schools you need to run forEach on "json.school" which is an Array, not on "json" variable which has an object data.