HTML table to array javascript

HTML table to array javascript

本文关键字:javascript array to table HTML      更新时间:2023-09-26

我以前发现了这个问题,这里是答案,但我不能使它工作。问题是,我想用javascript

将表格中的所有值都放到数组中

HTML表:

<table id="cartGrid">
  <thead>
       <tr>
          <th>Item Description</th>
          <th>Qty</th>
          <th>Unit Price</th>
          <th>Ext Price</th>
       </tr>
  </thead>
<tbody>
    <tr><td>Old Lamp</td><td>1</td><td>107.00</td><td>107.00</td>
    <tr><td>Blue POst</td><td>2</td><td>7.00</td><td>14.00</td>
</tbody>
</table>
JavaScript:

var myTableArray = [];
$("table#cartGrid tr").each(function() {
    var arrayOfThisRow = [];
    var tableData = $(this).find('td');
    if (tableData.length > 0) {
        tableData.each(function() { arrayOfThisRow.push($(this).text()); });
        myTableArray.push(arrayOfThisRow);
    }
});
alert(myTableArray);

我找到了另一种方法——但是都返回一个空数组

var tableData = new Array();    
$('#cartGrid tr').each(function(row, tr){
    tableData[row]={
        "ItemDescription" : $(tr).find('td:eq(0)').text()
        , "Qty" :$(tr).find('td:eq(1)').text()
        , "UnitPrice" : $(tr).find('td:eq(2)').text()
        , "ExtPrice" : $(tr).find('td:eq(3)').text()
    }
}); 
tableData.shift();  // first row is the table header - so remove

做一些猜测,从你的帖子–不工作,代码,我建议使用jQuery:

// iterate over each of the <tr> elements within the
// <tbody>, using the map() method:
var details = $('tbody tr').map(function (i, row) {
    // creating an Object to return:
    return {
        // returning the key:value pair of
        // the hard-coded key-names against the
        // retrieved textContent (using the
        // HTMLTableRowElement's cells collection:
        'description': row.cells[0].textContent,
            'quantity': row.cells[1].textContent,
            'unitPrice': row.cells[2].textContent,
            'extPrice': row.cells[3].textContent
    }
// converting the map into an Array:
}).get();
console.log(details);

JS Fiddle demo.

或者,在纯JavaScript中:

// using Array.prototype.map(), with Function.prototype.call(), to treat
// the Array-like NodeList returned by document.querySelectorAll(), as an
// Array; iterating over the found <tr> elements within the <tbody>:
var details = Array.prototype.map.call(document.querySelectorAll('tbody tr'), function (row) {
    // the first argument of the anonymous function (here: 'row') is
    // the array-element of the array over which we're iterating.
    // here we return exactly the same as before:
    return {
        'description': row.cells[0].textContent,
            'quantity': row.cells[1].textContent,
            'unitPrice': row.cells[2].textContent,
            'extPrice': row.cells[3].textContent
    };
});
console.log(details);

引用:

  • JavaScript:
    • Array.prototype.map() .
    • Function.prototype.call() .
    • HTMLTableRowElement .
    • Node.textContent .
  • jQuery:
    • get() .
    • map() .

您也可以使用表的标题并从中创建一个'对象模板'。所以你可以这样写:

{ Item_Description: '', Qty: '', Unit_Price: '', Exit_Price: '' }

为了稍后映射行数据,您可以将每个键存储在一个数组中,以便您可以轻松地访问每一行。

请看看下面的演示和jsFiddle。

但是为什么需要从DOM中获取数据呢?我认为最好是通过ajax请求从后端获得JSON数据。

var tableData = [],
    objTmpl,
    objMap = [];
$("table#cartGrid tr").each(function() {
    var $row = $(this),
        key = '';
    
    //console.log($row.children().filter('th'));
    //check if heading
    var $headings = !objTmpl ? $row.children().filter('th'): []; // do this test only if objTmpl is undefined!
    //console.log($headings);
    if ( $headings.length > 0 ) {
        objTmpl = {};
        $headings.each(function(index) {
            key = $(this).text().replace(' ', '_'); 
            objTmpl[key] = '';
            objMap[index] = key;
        });
        //console.log('heading found', objTmpl, objMap);
    } else {
        // not heading --> data row
        var curRowDataObj = JSON.parse(JSON.stringify(objTmpl)); // copy tmpl.
        
        $row.children().each(function(index) {
            curRowDataObj[objMap[index]] = $(this).text();
        });
        
        tableData.push(curRowDataObj);
    }
});
//console.log(tableData);
$('#out').html(JSON.stringify(tableData, null, 4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="cartGrid">
  <thead>
       <tr>
          <th>Item Description</th>
          <th>Qty</th>
          <th>Unit Price</th>
          <th>Ext Price</th>
       </tr>
  </thead>
<tbody>
    <tr><td>Old Lamp</td><td>1</td><td>107.00</td><td>107.00</td></tr>
    <tr><td>Blue POst</td><td>2</td><td>7.00</td><td>14.00</td></tr>
</tbody>
</table>
<h2>Output data (debugging only):</h2>
<pre id="out"></pre>

此时此刻,最简单的办法就是:

var tableArray = [...document.querySelectorAll('table#cartGrid>*>tr')]
  .map(row => [...row.querySelectorAll('td,th')].map(cell => cell.innerText) );

,[…X]是将X隐式强制转换为数组。最后一个映射当然是可选的。