maymunskoa

From JSON to HTML Table

Jun 26th, 2020
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input){
  2.     const parsed = JSON.parse(input);
  3.     let outputArr = ['<table>'];
  4.     outputArr.push(makeKeyRow(parsed));
  5.     parsed.forEach(obj=>{
  6.         outputArr.push(makeValueRow(obj))
  7.     });
  8.     outputArr.push('</table>');
  9.  
  10.     function makeValueRow(obj){
  11.         let valBlock = '<tr>';
  12.         Object.entries(obj).forEach(pair=>{
  13.             let value = pair[1];
  14.             if(typeof value === 'string'){
  15.                 value = value.replace(/&/g, '&amp;')
  16.                      .replace(/</g, '&lt;')
  17.                      .replace(/>/g, '&gt;')
  18.                      .replace(/"/g, '&quot;')
  19.                      .replace(/'/g, '&#39;')
  20.             }
  21.            
  22.             valBlock += `<td>${value}</td>`
  23.         });
  24.         valBlock +='</tr>';
  25.         return valBlock;
  26.     }
  27.  
  28.     function makeKeyRow(arr) {
  29.         let keyRow = '<tr>';
  30.         Object.keys(arr[0]).forEach(key=>
  31.                 keyRow += `<th>${key}</th>`
  32.    
  33.             );
  34.         keyRow += '</tr>';
  35.         return keyRow;
  36.     }
  37.  
  38.  
  39.    
  40.     return outputArr.join('\n');
  41. }
Advertisement
Add Comment
Please, Sign In to add comment