So basically what I am trying to do is target a specific key in a parsed JSON file in AJAX using a GET request and then try to print it to the DOM in a list using a button. But when I try to target the specific key whose data I am supposed to print it returns undefined. Here's the code that I have written:
getFruitsBtn.addEventListener('click', function(){
let xhr = new XMLHttpRequest();
xhr.open('GET' , 'fruits.JSON' , true)
xhr.onprogress = function(){
console.log('Getting work done')
}
xhr.onload = function(){
if(this.status==200){
let fruitObj = JSON.parse(this.responseText)
console.log(fruitObj)
let getFruitList = document.getElementById('fruitList')
let str = ''
for(key in fruitObj){
console.log(fruitObj[key].name)
str += `<li>${fruitObj[key].name}</li>`
}
getFruitList.innerHTML = str
}
else{
console.log('Sorry something went wrong.')
}
}
xhr.send()
})
I want to print the data stored in the key "name" from the JSON file which I am targeting :
{"fruits" : [{"name" : "Apple"
},
{
"name" : "Mango"
},
{
"name" : "Orange"
},
{
"name" : "Peach"
},
{
"name" : "Almond"
},
{
"name" : "Lemon"
}
]}
I will be more than thankful for a simple answer.
console.log(fruitObj)executed?