Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function JSONtoHtmlTable(jsonString){
- let result = '<table>';
- const arr = JSON.parse(jsonString);
- const titleSet = new Set(arr.map(i => Object.keys(i)).flat());
- const titleArray = Array.from(titleSet);
- result += '<tr></th>' + titleArray.join('</th><th>') + '</th></tr>';
- result = arr.reduce((acc,currItem)=>{
- let innerResult = titleArray.reduce((titleAcc,currTitle)=>{
- const value = currItem[currTitle];
- value = value === undefined ? '' :
- value.replace(/&/g,'&')
- .replace(/</g,'<')
- .replace(/>/g,'>')
- .replace(/"/g,""")
- .replace(/'/g,''')
- return titleAcc + '<td>' + value + '</td>';
- },'');
- if(innerResult === ''){ return acc; }
- return acc + '<tr>' + innerResult + '</tr>';
- },result);
- return result + '</table>'
- }
- JSONtoHtmlTable('[{"Name":"Tomatoes & Chips","Price":2.35},{"Name":"J&B Chocolate","Price":0.96}]');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement