I have this array:
var employees = [
{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },
{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },
{ \"firstName\
A reusable JSON to table conversion solution for objects in an array type of data structure. Object properties are inserted at the header cells and the values are inserted at the data cells. Sorry for my unorthodox indenting but it makes me feel comfortable with functional programming.
var employees = [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName": "Jones" }
],
goods = [
{ "ID":"0001" , "Description":"Cool Table", "Price":"499" , "Color":"Green" },
{ "ID":"0002" , "Description":"Ceramic Vase", "Price":"120" , "Color":"Beige" },
{ "ID":"0003" , "Description":"Titanium Ashtray", "Price":"999" , "Color":"Titanium Color" },
{ "ID":"0004" , "Description":"Story Book", "Price":"1" , "Color":"Yellow" },
{ "ID":"0005" , "Description":"Chair", "Price":"120" , "Color":"Pink" }
],
tableMaker = o => {var keys = Object.keys(o[0]),
rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "" + t + ">"
: "<" + t + ">" + c + "" + t + ">"),""),
rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),rowMaker(keys,"th"));
return "" + rows + "
";
};
document.write(tableMaker(employees));
document.write(tableMaker(goods));
- 热议问题