http://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects/19101235#19101235
http://jsfiddle.net/3rmstg5p/7/
<h2><a href="http://stackoverflow.com/questions/30252632/">Bind datatable to nested json object</a></h2>
<table id="table">
<thead>
<tr>
<th data-field="EmployeeID">ID</th>
<th data-field="FirstName">Firstname</th>
<th data-field="Position.PositionID">PositionID</th>
<th data-field="Position.PositionName">PositionName</th>
</tr>
</thead>
</table>
<pre>
<code>
public class Class1 {
public string EmployeeID { get; set; }
public string FirstName { get; set; }
public Position Position { get; set; }
public Class1 GetEmployees()
{
return this;
}
}
public class Position {
public string PositionID { get; set; }
public string PositionName { get; set; }
//Other functions below
}
</code>
</pre>
var data = [
{
"EmployeeID": "12**3",
"FirstName": "Marc",
"Position": {"PositionID": 1, "PositionName": "Supermarket"}
},
{
"EmployeeID": "456",
"FirstName": "Scott",
"Position": {"PositionID": 2, "PositionName": "Googleplex"}
},
{
"EmployeeID": "789",
"FirstName": "John",
"Position": {"PositionID": 3, "PositionName": "SanFran"}
}
];
function flattenJson(data) {
var result = {};
function recurse (cur, prop) {
if (Object(cur) !== cur) {
result[prop] = cur;
} else if (Array.isArray(cur)) {
for(var i=0, l=cur.length; i<l; i++)
recurse(cur[i], prop + "[" + i + "]");
if (l == 0)
result[prop] = [];
} else {
var isEmpty = true;
for (var p in cur) {
isEmpty = false;
recurse(cur[p], prop ? prop+"."+p : p);
}
if (isEmpty && prop)
result[prop] = {};
}
}
recurse(data, "");
return result;
}
$(function () {
flattenedData = jQuery.map( data, function(d){ return flattenJson(d) });
jQuery.each(data, flattenJson);
$('#table').bootstrapTable({
data: flattenedData
});
console.log(flattenedData);
});
留言列表