Monday, April 22, 2013

Rendering a JSON array as Table


http://stackoverflow.com/questions/1876485/get-property-names-in-json-objects

    function renderData() {
        var obj = { 'players': [
            { 'fname': 'joe', 'lname': 'smith', 'number': '34' },
            { 'fname': 'jim', 'lname': 'jones', 'number': '12' },
            { 'fname': 'jack', 'lname': 'Hoff', 'number': '84' }
            ] };

        var cols = GetHeaders(obj);

        $('#Output').html(CreateTable(obj, cols));
    }


    function CreateTable(obj, cols) {
        var table = $('<table></table>');
        var th = $('<tr></tr>');
        for (var i = 0; i < cols.length; i++) {
            th.append('<th>' + cols[i] + '</th>');
        }
        table.append(th);

        for (var j = 0; j < obj.players.length; j++) {
            var player = obj.players[j];
            var tr = $('<tr></tr>');
            for (var k = 0; k < cols.length; k++) {
                var columnName = cols[k];
                tr.append('<td>' + player[columnName] + '</td>');
            }
            table.append(tr);
        }
        return table;
    }



    function GetHeaders(obj) {
        var cols = new Array();
        var p = obj.players[0];
        for (var key in p) {
            //alert(' name=' + key + ' value=' + p[key]);
            cols.push(key);
        }
        return cols;
    }

No comments:

Post a Comment

How to check local and global angular versions

 Use the command ng version (or ng v ) to find the version of Angular CLI in the current folder. Run it outside of the Angular project, to f...