Reputation: 8376
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
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
Reputation: 2288
Couple of problems.
for(dd in diferencias[d])
<td>
tags as well.var tr
before you use it (tr += r
)Upvotes: 1