0

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.

4
  • print to console what is returned from the xhr call Commented Aug 21, 2021 at 16:48
  • What did you see in the console when console.log(fruitObj) executed? Commented Aug 21, 2021 at 16:49
  • @frogcoder When I print it into the console I get an array with 6 entries in which the data of my JSON file is stored in form of object literals. Commented Aug 22, 2021 at 3:39
  • @balderman I tried printing the data to the console and it gets the data correctly in form of object literals stored in an array but when I try to target the key 'name' of those object literals it returns undefined. I have updated the question an also added the JSON file from which I am targeting data. Commented Aug 22, 2021 at 3:55

2 Answers 2

1

The data you want is in the fruitObj.fruits attribute. It's an array of object with attribute of name. Here is the code you can use.

let str = '';
for (fruit of fruitObj.fruits) {
  console.log(fruit.name);
  str += `<li>${fruit.name}</li>`
}

You can also do it without a loop.

let str = fruitObj.fruits.map(fruit => `<li>${fruit.name}</li>`).join('');
Sign up to request clarification or add additional context in comments.

Comments

0

just loop over the array

fruitObj.fruits.map((fruit)=>{
    console.log(fruit.name)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.