【问题标题】:How to read an html table into an array of objects?如何将 html 表格读入对象数组?
【发布时间】:2018-03-02 12:33:33
【问题描述】:

在我的角度量角器 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();
});

【问题讨论】:

  • stackoverflow.com/questions/29501976/… 似乎对我不起作用,因为我没有使用 ng-repeater 创建表。
  • 你不需要中继器,你也可以根据其他选择器获取元素列表..
  • 你所拥有的是正确的,你只需要创建对象而不是仅仅在列上映射

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


【解决方案1】:

对于您的具体示例,您可以将 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 循环替换为数组方法来进一步折叠这一点,但我将其保留为这样,因为它可能更容易理解。

【讨论】:

  • 非常感谢!但是,目前量角器抱怨:Failed: document is not defined
  • 如果可能,我更喜欢使用th 元素生成名称的解决方案。但是,我可以尝试自己弄清楚。类型安全(年龄作为数字)对我来说不是优先事项。
  • 您可以对thead &gt; tr &gt; th 元素执行类似的操作来获取名称。
  • 确实对我有帮助,但是我们怎样才能让它动态化,比如姓名、年龄、性别等列应该动态出现
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
相关资源
最近更新 更多