-2

I Have a JSON data file like below and I would like to load all objects under the utility into a table but I am not even able to load first row into the table!

Can you please take a look at this and let me know what I am doing wrong? and how I can loop trough all utility objects and load them in a seperate table <tr>

var data = {
  "utility": {
    "Water": {
      "account": "99999",
      "balance": "5555",
      "owner": "Fred"
    },

    "Phone": {
      "account": "7777",
      "balance": "6666",
      "owner": "Mark"
    },

    "Power": {
      "account": "A9885",
      "balance": "2222",
      "owner": "Suzan"
    }
  },

  "clients": {
    "David": {
      "account": "99999",
      "balance": "5555",
      "Date": "Jan 11"
    },

    "George": {
      "account": "7777",
      "balance": "6666",
      "Date": "March 22"
    },

    "Marco": {
      "account": "A9885",
      "balance": "2222",
      "Date": "Feb 25"
    }
  }

}

var obj = JSON.parse(data);
$(".container").append(
  '<table class="table table-hover"><tr><td>' + 
  obj.Water.account + 
  '</td><td>99999</td><td>5555</td><td>Fred</td></tr></table>'
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
jherax
  • 5,238
  • 5
  • 38
  • 50
Behseini
  • 6,066
  • 23
  • 78
  • 125

5 Answers5

1

Once you have parsed the JSON, it's just a standard object. Loop through it as such:

 // Loop through the utility property:
 for(var p in data.utility){

    // Loop through the properties of the utility property:
    for(var p2 in data.utility[p]){
        var row = document.createElement("tr");

        // Loop through the properties of the found property
        for(var p3 in data.utility[p][p2]){
            var cell - document.createElement("td");
            cell.innerHTML = p3 + " = " + data.utility[p][p2][p3];
        }
        row.appendChild(cell);
    }
    // Use appendChild to append row to table.
 }
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
1

Hopefully this is how you want. Tell me if you want improved.

var data =
  {
    "utility": {
                 "Water": {
                  "account": "99999",
                  "balance": "5555",
                  "owner": "Fred" 
                },
                
                 "Phone": {
                  "account": "7777",
                  "balance": "6666",
                  "owner": "Mark" 
                },  
                  
                 "Power": {
                  "account": "A9885",
                  "balance": "2222",
                  "owner": "Suzan" 
                } 
    },
      
    "clients": {
                 "David": {
                  "account": "99999",
                  "balance": "5555",
                  "Date": "Jan 11" 
                },
                
                 "George": {
                  "account": "7777",
                  "balance": "6666",
                  "Date": "March 22" 
                },  
                  
                 "Marco": {
                  "account": "A9885",
                  "balance": "2222",
                  "Date": "Feb 25" 
                } 
    }
    
}

var utils = data.utility;
var tableStr='';
$.each(utils,function(key,value){
    tableStr +="<tr>";
    tableStr +="<td>"+key+"</td>";
    $.each(value,function(k,v){
      tableStr +="<td>"+k+"</td><td>"+v+"</td>";
    });
  tableStr +="</tr>";
});
$("#tbl").html(tableStr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <table  class="table table-hover" id="tbl">
    </table>
</div>
pritesh
  • 533
  • 4
  • 15
0

As you add the jQuery tag, I provide you this approach:

  //if you have a JSON (string)
  //var obj = JSON.parse(data);

  var prop1, prop2, inner,
      $table = $('<table>').addClass('table table-hover'),
      $tr, $td;

  //loop over 'utility' properties
  for (prop1 in data.utility) {
    $tr = $('<tr>');
    inner = data.utility[prop1];
    for (prop2 in inner) {
      $td = $('<td>').text(inner[prop2]).appendTo($tr);
    }
    $tr.appendTo($table);
  }

  $table.appendTo(".container");
jherax
  • 5,238
  • 5
  • 38
  • 50
0

as mentioned above, you dont need to parse your data. so this snippet should do it for you:

//just use you data array you have above.
jQuery(document).ready(function(){
    var result = "<table>";
    for (var item in data.utility) {
        result += "<tr><td>" + item + ":</td>";
        console.log(item);
        for (var subItem in data.utility[item]) {
            result += "<td>" + data.utility[item][subItem] + "</td>";
        }
        result += "</tr>";
    }
    result+="</table>";
    jQuery(".container").append(result);
});

let me know if it works for you.

Nicensin
  • 943
  • 1
  • 6
  • 15
-1

Please, read an article from MDN, because it describes a difference between methods:

  • in
  • for..in
  • Object.keys
  • Object.getOwnPropertyNames
  • Object.getOwnPropertyDescriptors

Also have a look at the method:

The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

Examples from MDN:

var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array like object with random key ordering
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(an_obj)); // console: ['2', '7', '100']

// getFoo is property which isn't enumerable
var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
my_obj.foo = 1;

console.log(Object.keys(my_obj)); // console: ['foo']

The Object.getOwnPropertyNames() method returns an array of all properties (enumerable or not) found directly upon a given object.

Examples from MDN:

var arr = ['a', 'b', 'c'];
console.log(Object.getOwnPropertyNames(arr).sort()); 
// logs ["0", "1", "2", "length"]

// Array-like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.getOwnPropertyNames(obj).sort()); 
// logs ["0", "1", "2"]

// Logging property names and values using Array.forEach
Object.getOwnPropertyNames(obj).forEach(function(val, idx, array) {
  console.log(val + ' -> ' + obj[val]);
});
// logs
// 0 -> a
// 1 -> b
// 2 -> c

// non-enumerable property
var my_obj = Object.create({}, {
  getFoo: {
    value: function() { return this.foo; },
    enumerable: false
  }
});
my_obj.foo = 1;

console.log(Object.getOwnPropertyNames(my_obj).sort()); 
// logs ["foo", "getFoo"]
StuS
  • 817
  • 9
  • 14