您好,您可以这样做:
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内部thAND 是tr您的表的第一个。由您决定将此代码更改为另一种行为
在线样品