diegoaguilar
diegoaguilar

Reputation: 8376

How to iterate over JSON object in JavaScript and create table with it?

I have a JSON with this structure:

diferencias = {
    "1": {
      "1": 543.0, 
      "0": 542.0
    }, 
    "2": {
      "0 1": 0.3333333333333333
    }
}

I need to obtain a table with outer keys as columns.

I wrote the following code:

$("#pinchetabla").empty()
    var tr = ""
    for (d in diferencias) {
        var r = ''
        for (dd in d) {
            //console.log(dd)
            r += '<tr>' + 'f[' + diferencias.dd + ']=' + diferencias.d.dd + '</tr>'
        }
        tr += r
    }

    var table = "<table id='resultados' class='table table-condensed'>" + tr + "</table>"
$("#pinchetabla").append(table)

I've got following jsfiddle

Where pinchetabla is a div. However I can't even properly access the JSON keys and values. What am I missing?

Upvotes: 0

Views: 182

Answers (2)

thefourtheye
thefourtheye

Reputation: 239473

When you access properties with dot notation, like this object.propertyname, JavaScript will look for propertyname in the object. In your case, d and dd are mere keys in the object, but JavaScript will be looking for them in the diferencias and fails to find them.

In order to access the properties dynamically, you have to use subscript/bracket notation, like this

r += '<tr>' + 'f[' + d + ']=' + diferencias[d][dd] + '</tr>';

Also the for loop should be like this

for (dd in diferencias[d]) {

Your table creation code can be fixed like this

var tr = "";
for (d in diferencias) {
    var r = '<tr>';
    for (dd in diferencias[d]) {
        r += '<td>' + 'f[' + d + ']=' + diferencias[d][dd] + '</td>';
    }
    tr += r + '</tr>';
}

Upvotes: 3

doog abides
doog abides

Reputation: 2288

Couple of problems.

  1. When you iterate a dictionary in javascript it returns the keys. So your inner iteration loop should be for(dd in diferencias[d])
  2. You need <td> tags as well.
  3. You need to instantiate var tr before you use it (tr += r)

http://jsfiddle.net/fQ9Py/1/

Upvotes: 1

Related Questions