Android2841
Android2841

Reputation: 55

dynamically name the column in the dataTable with JSON data

I need to find the way to parse this data so that i can dynamically name the column based on the JSON

I am using jquery dataTable

[  
   {  
      "2":{  
         "Department Number":{  
            "column":"Department Number",
            "department":"100"
         }
      },
      "1":{  
         "Department Number":{  
            "column":"Department Number",
            "department":"200"
         },
          "Department Name":{  
               "column":"Department Name",
               "department":"STMS"
          }

      }
   }
]

so that all the data in the dataTable looks like this

id    department number    department name
2     100
1     200                  STMS

I am using the coldfusion and javascript .Here is the code for it

<cfoutput>var data=#serializeJSON(dataJSON.getDepatmentData())#;</cfoutput> 


var sysAdmin = new listDataHandler(); 
var dtColumns = [{title:"id"} 
                                ,{title:data[0]} 
                               ,{title:"data[1]"} 
               ] 


var oTable = $("#departmentTable").DataTable({columns:dtColumns,data:data.DATA 
 }); 

I hope i have explained myself well here

Upvotes: 0

Views: 124

Answers (1)

Barmar
Barmar

Reputation: 780724

Go through all the objects in the JSON and create an array of the unique property names.

var colsObj = {};
for (id in data[0]) {
    for (prop in data[0][id]) {
        colsObj[prop] = true;
    }
}
var dtColumns = [{title: 'id'}].concat(Object.keys(colsObj).map(function(name) {
    return {title: name};
}));

Upvotes: 1

Related Questions