通过遍历表行创建对象数组 [英] Create an array of objects by iterating through table rows

查看:68
本文介绍了通过遍历表行创建对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTML表,我想遍历它的行并创建一个集合,或者说一个对象数组".

I have an HTML table and I want to iterate through its rows and create a collection or lets say an "array of objects".

例如:

<table id="tbPermission">
  <tr>
    <th>User ID</th>
    <th>User Name</th>
  </tr>
  <tr>
    <td>1</td>
    <td>Test1</td>
  </tr>
</table>

我要创建一个如下的集合:

I want to create a collection as below:

var trArray = [];
$('#tbPermission tr').each(function () {
    var tdArray = [];
    $(this).find('td').each(function () {

        // I want to create the array of objects here …
        tdArray.push();
    });

    // Final array
    trArray.push(tdArray);
});

数组可能如下所示:

tdArray : {'UserID' : '1', 'UserName' : 'Test1'};

和:

trArray : [
    {'UserID' : '1', 'UserName' : 'Test1'},
    {'UserID' : '2', 'UserName' : 'Test2'}
]

推荐答案

尝试此代码

var trArray = [];
$('#tbPermission tr').each(function () {
    var tr =$(this).text();  //get current tr's text
    var tdArray = [];
    $(this).find('td').each(function () {
        var td = $(this).text();  //get current td's text
        var items = {}; //create an empty object
        items[tr] = td; // add elements to object 
        tdArray.push(items); //push the object to array
    });    
});

在这里,我刚刚创建了一个空对象,使用tr和td的引用填充对象,然后将该对象添加到最终数组中.

Here, I just created an empty object, filled object with references of tr and td, the added that object to the final array.

添加有效的 jsfiddle

这篇关于通过遍历表行创建对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆