Search code examples
jqueryjsontabular

jQuery and JSON: break object into a table


I need a little bit of help navigating through this object:

{"COLUMNS":["ID","TYPE","NAME"],"DATA":[[1,"Image","My Image"],[2,"Text","My Text"],[3,"Video","My Video"],[4,"video","test"],[5,"Image","testName"],[6,"Image","testName"],[7,"Image","testName"],[8,"Image","testName"],[9,"Image","testName"],[10,"Image","testName"]]}

What would be the best way to loop over this object in order to display it like so:

ID  | Type   | Name
1     Video    My Video
...   ...      ...

This JSON object is clearly a query result... a lot of queries will need to be displayed as tabular data like this, so perhaps I should create a class (function) that handles this result.


Solution

  • headers = obj["COLUMNS"];
    $(headers).each(function(index,item){ /* do something interesting */ });
    data    = obj["DATA"];
    $(data).each(function(index,item){ /* do something interesting */ });
    

    "Something interesting" in this case would be to create new TH and TD elements from the headers, TR and TD elements from the data rows.

    (You could of course do

    $(obj["COLUMNS"]).each(...)
    

    if you don't need the headers and data separately later. Sometimes I think people go a little overboard with the functional model, sacrificing clarity.)