HTML表到数组javascript

HTML表到数组javascript,javascript,jquery,html,arrays,Javascript,Jquery,Html,Arrays,我以前发现过这个问题,下面是答案,但我无法让它起作用。 所以问题是:我想使用javascript将表中的所有值都放到数组中 HTML表格: <table id="cartGrid"> <thead> <tr> <th>Item Description</th> <th>Qty</th> <th>Unit Price</

我以前发现过这个问题,下面是答案,但我无法让它起作用。 所以问题是:我想使用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>

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

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);
//迭代
//,使用map()方法:
var details=$('tbody tr').map(函数(i,行){
//创建要返回的对象:
返回{
//返回的键:值对
//根据
//检索到的文本内容(使用
//HTMLTableRowElement的单元格集合:
“说明”:行。单元格[0]。文本内容,
“数量”:行。单元格[1]。文本内容,
“单价”:行。单元格[2]。文本内容,
“extPrice”:行。单元格[3]。文本内容
}
//将地图转换为数组:
}).get();
控制台日志(详细信息);

或者,在纯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);
//使用Array.prototype.map()和Function.prototype.call()处理
//document.querySelectorAll()返回的类数组NodeList,作为
//数组中找到的元素进行迭代:
var details=Array.prototype.map.call(document.querySelectorAll('tbody tr'),函数(行){
//匿名函数(此处为:“行”)的第一个参数是
//我们迭代的数组的数组元素。
//在这里,我们返回与之前完全相同的结果:
返回{
“说明”:行。单元格[0]。文本内容,
“数量”:行。单元格[1]。文本内容,
“单价”:行。单元格[2]。文本内容,
“extPrice”:行。单元格[3]。文本内容
};
});
控制台日志(详细信息);
参考资料:

  • JavaScript:
  • jQuery:

您还可以获取表的标题,并从中创建“对象模板”。因此,您可以使用以下内容:

{ Item_Description: '', Qty: '', Unit_Price: '', Exit_Price: '' }
为了以后映射行数据,可以将每个键存储在一个数组中,这样就可以轻松地访问每一行的键

请看下面的演示和这里的

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

var tableData=[],
objTmpl,
objMap=[];
$(“表#cartGrid tr”)。每个(函数(){
var$row=$(此),
键='';
//log($row.children().filter('th'));
//检查标题是否正确
var$headers=!objTmpl?$row.children().filter('th'):[];//仅当objTmpl未定义时才执行此测试!
//console.log($标题);
如果($headers.length>0){
objTmpl={};
$headers.每个(功能(索引){
key=$(this.text().replace('''.'');
objTmpl[键]='';
objMap[index]=键;
});
//log('heading found',objTmpl,objMap);
}否则{
//非标题-->数据行
var curRowDataObj=JSON.parse(JSON.stringify(objTmpl));//复制tmpl。
$row.children().each(函数(索引){
curRowDataObj[objMap[index]]=$(this.text();
});
tableData.push(curRowDataObj);
}
});
//console.log(tableData);
$('#out').html(JSON.stringify(tableData,null,4));

项目说明
数量
单价
外部价格
旧灯1107.00107.00
蓝色邮政27.0014.00
输出数据(仅限调试):

此时,最短的路径是:

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

其中,[…x]是x到数组的隐式转换。最后一个映射当然是可选的。

您还可以显示您想要获得的输出吗?我想得到以下内容:TalbeData[1]“ItemDescription:”旧灯“,”数量“:”1“,”单价“:”107“,”ExtPrice”:'107'您能提供原始问题的链接吗?@SlavikOstapenko原始问题/答案使用JQuery-是吗?我真的很感谢您的时间,但它仍然返回一个空数组谢谢您,我真的很感谢您的时间和努力!没问题;我很高兴能提供帮助。我为什么使用DOM?这是我要完成的任务have:1.有一个包含8个字段的表单,其中一个是date。当您填写表单时,所有数据都会进入DB(数据库)2.如果date==today->checked=true 3.用户有机会检查/取消检查数据行4.所有检查的数据行都必须写入txt文件--------所以我想做的是让用户检查/取消检查,然后我将通过DOM将该信息放入数组,然后将其从数组解析为txt文件。您不必使用DOM来管理您的数据。将它们保存在javascript中并在那里执行所需的检查。请查看以下内容。jQuery也可以这样做,但可能需要更多的编码。(日期检查不在演示中,而是用于所选项目和文本文件生成的筛选器。)
var tableArray = [...document.querySelectorAll('table#cartGrid>*>tr')]
  .map(row => [...row.querySelectorAll('td,th')].map(cell => cell.innerText) );