Looping through JSON data to populate a table

Good afternoon all, I have a json file of US states and their abbreviations (can be found here https://gist.github.com/mshafrir/2646763) and I want to use that to create a table with two columns, first column with the abbreviations, and the second with the state name.

Any suggestions on how to do that? There are a few suggestions on stack overflow that I have tried without much success, for e.g. this one: https://stackoverflow.com/questions/30464675/create-table-from-json-pure-javascript

Post what code you have tried and we can try to help guide you to a solution.

var stateArray = JSON.parse(states json data here).

function addHeaders(table, keys) {
  var row = table.insertRow();
  for( var i = 0; i < keys.length; i++ ) {
    var cell = row.insertCell();
    cell.appendChild(document.createTextNode(keys[i]));
  }
}

var table = document.createElement('table');
for( var i = 0; i < stateArray.length; i++ ) {

  var state = stateArray[i];
  if(i === 0 ) {
    addHeaders(table, Object.keys(child));
  }
  var row = table.insertRow();
  Object.keys(state).forEach(function(k) {
    console.log(k);
    var cell = row.insertCell();
    cell.appendChild(document.createTextNode(child[k]));
  })
}

document.getElementById('tables').appendChild(table)

This is what I tried so far.

Well, in the browser console, you will see the following error:

Uncaught ReferenceError: child is not defined

This corresponds to the following line:

addHeaders(table, Object.keys(child));

You have not defined a variable named child. What is child suppose to be?

Hey Randell, that should say state as the local variable rather than child. Even when I have changed that in my code, I am still not seeing a table as expected.

Are you seeing any errors in the browser console?

What are using seeing displayed?

When I changed child to state in both places of the code and define stateArray as the following:

var stateArray = [
  {
    name: "Alabama",
    abbreviation: "AL"
  },
  {
    name: "Alaska",
    abbreviation: "AK"
  },
  {
    name: "American Samoa",
    abbreviation: "AS"
  }
];

I see:
image

This is what I see (abbreviation and name repeated many times over):

What does the code around line 262 look like?

document.getElementById("tables").appendChild(table)

Do you have an element with id=“tables”?