0

I have a list of json object, with the attributes: first name, last name, and gender. I have a fetch function as such:

buttonsend.addEventListener("click", function(){
fetch("http://uinames.com/api/?amount=25&region=denmark&gender=female").then(
    function(response){
        return response.json();
    }
        ).then(function(jsonData){
            for(var i = 0; i <= jsonData.length; i ++){
                console.log(JSON.stringify(jsonData[i]).gender);
            }
            //document.getElementById("json").innerHTML = JSON.stringify(jsonData);

            console.log(2);

        });
    });

In my for loop how can I access each of the elements of the object, and display them in a table in my HTML code?

1
  • You have to do something like this first var data = JSON.parse(jsonData) and then do the loop and simply data[i].theAttributeYouWant. Also you’re trying to use stringify which converts it to text and not to an object. Your loop is not working because you’re trying to iterate a text, not a list of objects. Commented Sep 29, 2018 at 19:34

1 Answer 1

1

Simple solution to your problem (vanilla ES6):

fetch('http://uinames.com/api/?amount=25&region=denmark&gender=female')
  .then(res => res.json()) // returns response data as JSON object
  .then(jsonData => {
    const destinationTable = document.querySelector('table'); // select table to which you want to append the data
    jsonData.forEach(record => {
      const tr = document.createElement('tr'); // create a table row
      const tdGender = document.createElement('td'); // create a table cell
      tdGender.innerText = record.gender; // insert gender to the created table cell
      tr.appendChild(tdGender); // append table cell to the created row
      destinationTable.appendChild(tr); // append created row to the table
    })
  });

This solution assumes that you have a table with the proper headers set up somewhere in your HTML document. It itterates through the records returned by the server and creates table row containing the table cell with gender value for each one of them.

Sign up to request clarification or add additional context in comments.

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.