我想将HTML表转换为角度为2的jSON数组

时间:2018-04-27 14:08:26

标签: javascript json angular typescript

我尝试了一些方法但无法获得所需的输出。

这是我的表格

<table>
   <tr> 
    <th> Name </th> 
    <th> Age </th> 
   </tr>
   <tr>  
     <td> foo </td> 
     <td> 20 </td> 
   </tr>
   <tr> 
      <td> Boo </td> 
      <td> 24 </td> 
   </tr>
</table>

我想要所需的jSON输出如下

[{  
  Name: 'Foo',
  Age: 20
},{
  Name: 'Boo',
  Age: 24
}]

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

你好,你可以这样做:

const html = `<tr> 
<th> Name </th> 
<th> Age </th> 
</tr>
<tr>  
 <td> foo </td> 
 <td> 20 </td> 
</tr>
<tr> 
  <td> Boo </td> 
  <td> 24 </td> 
</tr>`;
// For plug and play sample, i just create dummy table.
const tableEl = document.createElement('table');
tableEl.innerHTML = html;


const output = [];
// Little trick to make querySelectorAll as iterable by foreach.
[].forEach.call(
    tableEl.querySelectorAll('tr'),
    //Uncomment for TypeScript strong type : (lineElement: HTMLElement) => {
    (lineElement) => {
        const rows = lineElement.querySelectorAll('td');
        if(rows.length >= 2) {
            output.push(
                {
                    name : rows[0].innerText,
                    age : rows[1].innerText,
                }
            );
        }
    });

console.log(output);

__更新1:来自___

的动态属性检测
const html = `<tr> 
<th> Name </th> 
<th> Age </th> 
</tr>
<tr>  
 <td> foo </td> 
 <td> 20 </td> 
</tr>
<tr> 
  <td> Boo </td> 
  <td> 24 </td> 
</tr>`;
// For plug and play sample, i just create dummy table by programming way
const tableEl = document.createElement('table');
tableEl.innerHTML = html;

const output:any[] = [];
const keys: string[] = [];
// Little trick to make querySelectorAll as iterable by foreach.
[].forEach.call(
    tableEl.querySelectorAll('tr'),
    (lineElement: HTMLElement) => {
        const rows = lineElement.querySelectorAll('td,th');
        /**
         * If is th tag, we store all items to keys array.
         */
        if(rows[0].nodeName === 'TH') {
          //We replace remove all whitespace char from key.
          rows.forEach((e:HTMLElement) => keys.push(e.innerText.replace(/\s*/g,'')));
        }        
        else {
          // We craft dynamically item object.
          let item: any = {};
          keys.forEach((key, index) => {
              // We use keys array to populate it.
              item[key] = rows[index].innerHTML;
          });
          //We Store it
          output.push(item);
        }
    });

console.log(output);

免责声明:

此脚本假设您只有一个tr内置th并且是您表格的第一个tr。由您决定将此代码更改为另一种行为

Online sample