如何将html表读入对象数组?

时间:2018-03-02 12:33:34

标签: javascript angular typescript protractor end-to-end

在我的角度量角器e2e测试中,我想对这样的html片段做断言:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Gender</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Joe</td>
            <td>23</td>
            <td>M</td>
        </tr>
        <tr>
            <td>Mary</td>
            <td>26</td>
            <td>W</td>
        </tr>
        ...
    </tbody>
</table>

如何将其转换为像这样的JavaScript对象?

[
    {Name: 'Joe', Age: 23, Gender: 'M'},
    {Name: 'Mary', Age: 25, Gender: 'W'},
    ...
]

我尝试了这个,但它给了我一维数组:

const row = element.all(by.css('tr'));
const cells = row.all(by.tagName('td'));
return cells.map(function (elm) {
  return elm.getText();
});

1 个答案:

答案 0 :(得分:2)

对于您的具体示例,您可以将HTML转换为符合您需求的简单对象数组:

function isHTMLTableElement(elem: HTMLTableElement | HTMLElement) : elem is HTMLTableElement {
    return elem.tagName === 'TABLE';
}

const table = document.getElementById('test');
const result: {name: string, age: number, gender: string}[] = [];

if (isHTMLTableElement(table)) {
    const rows: HTMLElement[] = [].slice.call(table.querySelectorAll('tbody tr'));
    for (const row of rows) {
        const cells: HTMLElement[] = [].slice.call(row.querySelectorAll('td'));
        const [name, age, gender] = cells.map(c => c.innerText);
        result.push({
            name: name,
            age: +age,
            gender: gender
        });
    }

    console.log(JSON.stringify(result));
}

你可以通过用数组方法替换for循环来进一步折叠它,但是我把它留下来,因为它可能更容易理解。