Building A Table Using An Array From User Input
I have researched and researched and maybe I'm just missing it, but I'm a novice at javascript and still having trouble. Basically, I need to build a table using data from an html
Solution 1:
I often use the following tableMaker
function to generate table HTML. So the below code will generate a table for you. The generic tableMaker
function takes an array of an object or an array of multiple objects provided in the first argument. All objects should have same keys (properties) since these keys are used to create the table header (if the second argument is set to true) and the values are used to create each row. It will return an HTML table text.
vartableMaker = (o,h) => {var keys = Object.keys(o[0]),
rowMaker = (a,t) => a.reduce((p,c,i,a) => p + (i === a.length-1 ? "<" + t + ">" + c + "</" + t + "></tr>"
: "<" + t + ">" + c + "</" + t + ">"),"<tr>"),
rows = o.reduce((r,c) => r + rowMaker(keys.reduce((v,k) => v.concat(c[k]),[]),"td"),h ? rowMaker(keys,"th") : []);
return"<table>" + rows + "</table>";
};
myCars = [{Pos: 1, Make: "Toyota"}, {Pos: 2, Make: "Volvo"}, {Pos: 3, Make: "BMW"}, {Pos: 4, Make: "Mercedes"}] ,
table = tableMaker(myCars,true); // if second argument provided as truthy then headers generateddocument.write(table);
Post a Comment for "Building A Table Using An Array From User Input"