0

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?

1
  • Instead of for(dd in d) your need for (dd in diferencias[d]) for a start. Commented Mar 18, 2014 at 15:43

2 Answers 2

3

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>';
}
Sign up to request clarification or add additional context in comments.

Comments

1

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/

2 Comments

Thanks! Anny suggest to make table better, I actually would like to obtain a column for each outer key and its inner keys as subcolumns inside each. I'd thank you soo much
I kind of assumed you were just using the table to get a feel for the iteration. Although a bit ugly, this edit jsfiddle.net/fQ9Py/2 shows how to use <td rowspan=x> to group your rows by category. You could also create entire tables nested instead of just using rowspan, depends on what you want/need.

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.