使用javascript将HTML表格转换为数组

时间:2015-04-11 23:56:12

标签: javascript html

您好我有下表:

<tbody>
    <tr class="odd first-child">
        <td class="first-child account_name">Label 1</td>
        <td class="last-child balance">Amount 1</td>
    </tr>
    <tr class="even">
        <td class="first-child account_name">Label 2</td>
        <td class="last-child balance">Amount 2</td>
    </tr>
    <tr class="odd">
        <td class="first-child account_name">Label 3</td>
        <td class="last-child balance">Amount 3</td>
    </tr>
    <tr class="even">
        <td class="first-child account_name">Label 4</td>
        <td class="last-child balance">Amount 4</td>
    </tr>
    <tr class="odd">
        <td class="first-child account_name">Label 5</td>
        <td class="last-child balance">Amount 5</td>
    </tr>
</tbody>

我需要使用javascript将其转换为数组,以便“标签1”是值“金额1”的键,“标签2”是值“金额2”等的键。

我怎么能这样做?

谢谢!

2 个答案:

答案 0 :(得分:0)

您只需循环遍历节点即可。

&#13;
&#13;
var c = document.querySelectorAll('#tgt td');
var d = {};
for (var i = 0; i < c.length; i += 2) {
  d[c[i].innerHTML] = c[i + 1].innerHTML;
}
console.log(d);
&#13;
<table id="tgt">
  <tbody>
    <tr class="odd first-child">
      <td class="first-child account_name">Label 1</td>
      <td class="last-child balance">Amount 1</td>
    </tr>
    <tr class="even">
      <td class="first-child account_name">Label 2</td>
      <td class="last-child balance">Amount 2</td>
    </tr>
    <tr class="odd">
      <td class="first-child account_name">Label 3</td>
      <td class="last-child balance">Amount 3</td>
    </tr>
    <tr class="even">
      <td class="first-child account_name">Label 4</td>
      <td class="last-child balance">Amount 4</td>
    </tr>
    <tr class="odd">
      <td class="first-child account_name">Label 5</td>
      <td class="last-child balance">Amount 5</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以尝试使用以下javascript来模拟键/值对:

var trElements = document.getElementsByTagName('tr');
var keyValue = [];

for(var i = 0; i < trElements.length; i++)
{
    var tdElements = trElements[i].getElementsByTagName('td');
    keyValue.push({"key":tdElements[0].innerHTML,"value":tdElements[1].innerHTML});
}

使用以下html:

<body>
    <table>
        <tr>
            <td>Key1</td>
            <td>Value1</td>
        </tr>
        <tr>
            <td>Key2</td>
            <td>Value2</td>
        </tr>
    </table>
</body>

通过选择keyValue [i] .key或keyValue [i] .value,您可以获得键或值的值。我认为这是最简单的方法。我不认为js默认支持键值对。