Advertisement
Ivankooo1

JSON

Jun 2nd, 2020
905
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function JSONtoHtmlTable(jsonString){
  2.   let result = '<table>';
  3.  
  4.   const arr = JSON.parse(jsonString);
  5.   const titleSet = new Set(arr.map(i => Object.keys(i)).flat());
  6.   const titleArray = Array.from(titleSet);
  7.  
  8.   result += '<tr></th>' + titleArray.join('</th><th>') + '</th></tr>';
  9.  
  10.   result = arr.reduce((acc,currItem)=>{
  11.     let innerResult = titleArray.reduce((titleAcc,currTitle)=>{
  12.       const value = currItem[currTitle];
  13.       value = value === undefined ? '' :
  14.        value.replace(/&/g,'&amp;')
  15.             .replace(/</g,'&lt;')
  16.             .replace(/>/g,'&gt;')
  17.             .replace(/"/g,"&quot;")
  18.             .replace(/'/g,'&#39;')
  19.            
  20.       return titleAcc + '<td>' + value + '</td>';
  21.     },'');
  22.  
  23.     if(innerResult === ''){ return acc; }
  24.     return acc + '<tr>' + innerResult + '</tr>';
  25.   },result);
  26.  
  27.   return result + '</table>'
  28. }
  29.  
  30. JSONtoHtmlTable('[{"Name":"Tomatoes & Chips","Price":2.35},{"Name":"J&B Chocolate","Price":0.96}]');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement