Dynamic table from JSON using javascript

时间:2015-11-12 11:03:53

标签: javascript jquery json

I use the following json to develop a table structure. But I'm unable to go ahead on adding rows according to columns.

[
{
"authType": "BasicAuth",
"phases": [
  {
    "type": "Development",
    "keys":[{
      "username": "developer"
    },{
      "password": "password123"
    }]
  },
  {
    "type": "Testing",
    "keys":[{
      "username": "tester"
    },{
      "password": "password123"
    }]
  }
]
},
{
"authType": "AccessToken",
"phases": [
  {
    "type": "Development",
    "keys":[{
      "token": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "url": "/demo/developer"
    }]
  },
  {
    "type": "Testing",
    "keys":[{
      "token": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "url": "/demo/testing"
    }]
  }
]
},
{
"authType": "OAuth",
"phases": [
  {
    "type": "Development",
    "keys":[{
      "consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "url": "/demo/development"
    }]
  },
  {
    "type": "Testing",
    "keys":[{
      "consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
    },{
      "url": "/demo/testing"
    }]
  }
]
}
]

I use the following script to iterate over the json.

var subTable = '<div class="subtable"><table data-clicked-parent-row="'+ clickedCell.row
            +'" data-clicked-column="'+ clickedCell.column +'"><tr><th>Keys</th>';
    tableData.forEach(function(e){
        if(rowType == e.authType){
            var phases;
            e.phases.forEach(function(t){
                subTable += '<th>'+ t.type +'</th>'
            })
            return subTable + '</tr></table></div>';
        }
    })

The thing is, I'm unable to add rows to the table while iterating on the objects. The following is a static version of the table. how can i write a generic function to achive the following table structure. Please let me know any better way to write the iteration.

enter image description here

2 个答案:

答案 0 :(得分:1)

var data = {
    "Items": [
        { 
            "id": "A004"
            , "name": "ACC LR2"
            , "userId": ["1","2","3","4"]
        }, { 
            "id": "0001"
            , "name": "ABG IT"
            , "userId": ["8","9","10","11"]
        }
    ]
}

function getUserId(obj){
    result = []
    obj.Items.forEach( function(item, i){
        result.push(item.userId);
    });
    return result;
}

function getUserIdAll(obj){
    result = []
    obj.Items.forEach( function(item, i){
        result = result.concat(item.userId);
    });
    return result;
}

console.log( getUserId(data) );
console.log( getUserIdAll(data) );

var data = [
  {
    "authType": "BasicAuth",
    "phases": [
      {
        "type": "Development",
        "keys": [
          {
            "username": "developer"
          },
          {
            "password": "password123"
          }
        ]
      },
      {
        "type": "Testing",
        "keys": [
          {
            "username": "tester"
          },
          {
            "password": "password123"
          }
        ]
      }
    ]
  },
  {
    "authType": "AccessToken",
    "phases": [
      {
        "type": "Development",
        "keys": [
          {
            "token": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "url": "/demo/developer"
          }
        ]
      },
      {
        "type": "Testing",
        "keys": [
          {
            "token": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "url": "/demo/testing"
          }
        ]
      }
    ]
  },
  {
    "authType": "OAuth",
    "phases": [
      {
        "type": "Development",
        "keys": [
          {
            "consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "url": "/demo/development"
          }
        ]
      },
      {
        "type": "Testing",
        "keys": [
          {
            "consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
          },
          {
            "url": "/demo/testing"
          }
        ]
      }
    ]
  }
];

function objGetKeyVal(obj){
    for (var key in obj) {
        return [ key, obj[key] ];
    }
}

(function createTable(tableData){
    var table = '<table>';
    // tableHeader += '<caption>Caption</caption>';
    // Creating table header

    // table += '<tr>';
    // table += '<th>Keys</th>';
    // table += '<th>Development</th>';
    // table += '<th>Testing</th>';
    // table += '</tr>';

    // Sub tables iterator
    tableData.forEach(function(subTable, i){
        tableRows = [];     // Rows array for sub table

        table += '<tr><th>Keys</th>';   // Table headers creating

        subTable.phases.forEach(function(colData, icol){
            
            table += '<th>'+colData.type+'</th>';   // Creating table headers for each phases

            colData.keys.forEach(function(key, irow){  // Converts structured data to array of rows arrays of columns
                if( tableRows[irow] === undefined) { tableRows[irow] = []; }
                rowData = objGetKeyVal(key);
                tableRows[irow][0] = rowData[0];
                tableRows[irow][icol+1] = rowData[1];
            });

        });
        
        table += '</tr>';               // End table header cration

        // Now we have usual table array - need only convert it to HTML
        // table looks like: [ ['col1', 'col2', 'col3'], ['col1', 'col2', 'col3'] ]
        table += '<tr><th colspan="3">'+subTable.authType+'</th></tr>';
        tableRows.forEach(function(row){
            table += '<tr>';
            row.forEach(function(str){ 
                table += '<td>'+str+'</td>';
            });
            table += '</tr>';
        });
        
    });

    table += '</table>';
    $('body').append(table);
    
})(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

Use this function for render table with json. Observe this function works with simple json. For complex json necessary adapter this function

var tableData = [
    {
        "Name": "Kevin",
        "Adress": "Adress UHE, SC",
    },
    {
        "Name": "Jose",
        "Adress": "Adress KUK, CC",
    },
    {
        "Name": "Kevin",
        "Adress": "Adress CGH, JK",
    }
];

function compile(){
    var subTable = '', column = '', row = '';
    
    for(c in tableData[0])
        column += '<th>' + c + '</th>';
    
    for(item in tableData){
        row += '<tr>';
        for(c in tableData[0]) row += '<td>' + tableData[item][c] + '</td>';
        row += '</tr>';
    }
    console.log(row)
    return '<table border="solid 1px"><tr>' + column + '</tr>' + row + '</table>';
};
document.write(compile());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>