如何使用 jQuery 将 HTML 表格转换为 Javascript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12290927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:37:55  来源:igfitidea点击:

How to convert HTML table to Javascript Object with jQuery

javascriptjquery

提问by Oscar Jara

I am trying to convert this HTML table:

我正在尝试转换此 HTML 表:

enter image description here

在此处输入图片说明

Code:

代码:

<table id="students" border="1">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Grade</th>
        </tr>
    </thead>
    <tbody>
        <tr class="student">
            <td>Oscar</td>
            <td>23</td>
            <td>16.5</td>        
        </tr>
        <tr class="student">
            <td>Antonio</td>
            <td>32</td>
            <td>14</td>        
        </tr>
        <tr class="student">
            <td>Jessica</td>
            <td>21</td>
            <td>19</td>        
        </tr>
    </tbody>
</table>??????

Into a javascript object using jQuery:

使用 jQuery 进入一个 javascript 对象:

var tbl = $('table#students tr').map(function() {
  return $(this).find('td').map(function() {
    return $(this).text();
  }).get();
}).get();

The above code will output the following array:

上面的代码将输出以下数组:

["Oscar", "23", "16.5", "Antonio", "32", "14", "Jessica", "21", "19"]


Everything is good at this point but how can I do if I want the javascript objects inside the array to have the following structure:

此时一切都很好,但是如果我希望数组中的 javascript 对象具有以下结构,我该怎么办:

[{id:1, name: "Oscar", age: 23, grade: 16.5}, {id:2, name: "Antonio", age: 32, grade: 14}, {id:3, name: "Jessica", age: 21, grade: 19}]

enter image description here

在此处输入图片说明

Just to be more specific...

只是为了更具体.​​..

  • The idis obtained from the tr
  • The name, ageand gradevalues are obtained from each row
  • 所述id从得到的tr
  • nameagegrade值是从各行获得的


I made this jsfiddle to test:

我做了这个 jsfiddle 来测试:

http://jsfiddle.net/oscarj24/ptVDm/

http://jsfiddle.net/oscarj24/ptVDm/

Thanks

谢谢

回答by undefined

var tbl = $('#students tr:has(td)').map(function(i, v) {
    var $td =  $('td', this);
        return {
                 id: ++i,
                 name: $td.eq(0).text(),
                 age: $td.eq(1).text(),
                 grade: $td.eq(2).text()               
               }
}).get();

回答by lightswitch05

I needed this exact thing, except I needed more features to be able to override column names and ignore any hidden rows. I wrote a jQuery plugin that does just that, located here https://github.com/lightswitch05/table-to-json

我需要这个确切的东西,除了我需要更多功能来覆盖列名并忽略任何隐藏的行。我写了一个 jQuery 插件来做到这一点,位于这里https://github.com/lightswitch05/table-to-json

for your example you would do: (http://jsfiddle.net/ptVDm/118/)

对于您的示例,您将执行以下操作:(http://jsfiddle.net/ptVDm/118/

var table = $('#students').tableToJSON();

One thing to note is that the id's aren't part of the resulting object. You could just get the id from the object's array location. Or if you really needed it to be part of the object, you could create an hidden column for the ID's and then they would be included

需要注意的一件事是 id 不是结果对象的一部分。您可以从对象的数组位置获取 id。或者,如果您真的需要它成为对象的一部分,您可以为 ID 创建一个隐藏列,然后将它们包含在内

回答by Christian

The following should work:

以下应该工作:

var cols = [];
var result = [];
$('#students>thead>th').each(function(){
    cols.push($(this).text().toLowerCase());
});
$('#students>tbody>tr').each(function(id){
    var row = {'id': id+1};
    $(this).find('td').each(function(index){
        row[cols[index]] = $(this).text();
    });
    result.push(row);
});

console.log(result);

Basically, I find the object properties from the table head, next I create an object for each row, assigning values to property names as deduced from the earlier array.

基本上,我从表头中找到对象属性,接下来我为每一行创建一个对象,将值分配给从早期数组推导出的属性名称。

Some obvious flaws:

一些明显的缺陷:

  • If the table data actually differs for some reason, (eg; empty rows for cosmetic), this system will put empty objects in the resulting array.
  • If you use colspanattribute in the table, this system won't automatically replicate the same value in different object properties, but rather limit to setting up to the remaining <td>s.
  • 如果表数据由于某种原因实际上不同(例如;用于装饰的空行),该系统将在结果数组中放置空对象。
  • 如果colspan在表中使用attribute,本系统不会在不同的对象属性中自动复制相同的值,而是限制设置为剩余的<td>s。

Seeing Josiah's approach, it's probably faster than mine since mine tries to be smarter by finding property names. I would recommend his technique if you know for sure your table structure will not change. Otherwise, you would need something on the lines of my code.

看到 Josiah 的方法,它可能比我的更快,因为我试图通过查找属性名称来变得更聪明。如果您确定您的表结构不会改变,我会推荐他的技术。否则,您将需要我的代码行中的某些内容。

Oh, and for the sake of completeness, here's a JSFiddle with mine.

哦,为了完整起见,这里有一个 JSFiddle 和我的.

回答by Josiah Ruddell

See updatedfiddle. The additional array mapis unnecessary because you are looking for a literal object for your JSON at this point.

请参阅更新的小提琴。额外的数组map是不必要的,因为此时您正在为 JSON 寻找文字对象。

var data = $('table#students tbody tr').map(function(index) {
    var cols = $(this).find('td');
    return {
        id: index + 1,
        name: cols[0].innerHTML,            // use innerHTML
        age: (cols[1].innerHTML + '') * 1,  // parse int
        grade: (cols[2].innerHTML + '') * 1 // parse int
    };
}).get();

回答by Selvakumar Arumugam

Try below approach for n columns

尝试以下方法对 n 列

DEMO:http://jsfiddle.net/ptVDm/7/

演示:http : //jsfiddle.net/ptVDm/7/

var tblhdr = $('table#students th').map(function () {
    return $(this).text();
}).get();

console.log(tblhdr);

var tbl = $('table#students tbody tr').map(function(idx, el) {
    var td = $(el).find('td');
    var obj = {id: idx+1};

    //Can work on number of columns
    for (var i = 0; i < tblhdr.length; i++) {
        obj[tblhdr[i]] = td.eq(i).text();
    }

    return obj;
}).get();

console.log(tbl);

回答by RobG

Dunno if jQuery helps much in this case, here's a plain JS solution that is reasonably independent of the table structure. It just requires that the first row is a header (can be a different table section element or not) and the rows 1+ are data.

不知道 jQuery 在这种情况下是否有很大帮助,这里有一个简单的 JS 解决方案,它合理地独立于表结构。它只要求第一行是标题(可以是不同的表节元素,也可以不是),行 1+ 是数据。

The table can have as many columns or rows as you like, if there are rowspan or colspans in there it will mess with the result (but jQuery won't help you with that either).

该表可以有任意多的列或行,如果那里有 rowspan 或 colspans,它会弄乱结果(但 jQuery 也不会帮助你)。

It could easily be adapted to specifically use the header section for the property names and to ignore a footer section:

它可以很容易地调整为专门使用属性名称的标题部分并忽略页脚部分:

function tableToObj(table) {
  var rows = table.rows;
  var propCells = rows[0].cells;
  var propNames = [];
  var results = [];
  var obj, row, cells;

  // Use the first row for the property names
  // Could use a header section but result is the same if
  // there is only one header row
  for (var i=0, iLen=propCells.length; i<iLen; i++) {
    propNames.push(propCells[i].textContent || propCells[i].innerText);
  }

  // Use the rows for data
  // Could use tbody rows here to exclude header & footer
  // but starting from 1 gives required result
  for (var j=1, jLen=rows.length; j<jLen; j++) {
    cells = rows[j].cells;
    obj = {};

    for (var k=0; k<iLen; k++) {
      obj[propNames[k]] = cells[k].textContent || cells[k].innerText;
    }
    results.push(obj)
  }
  return results;
}