简体   繁体   English

如何使用jQuery从HTML表中将数据提取到关联数组中?

[英]How to extract data into associative array from HTML table using jQuery?

Suppose I have HTML like this, 假设我有这样的HTML,

<table id="Words">
<tr>
    <td class="cell">Hello</td>
    <td class="desc">A word</td>
</tr>
<tr>
    <td class="cell">Bye</td>
    <td class="desc">A word</td>
</tr>
<tr>
    <td class="cell">Tricicle</td>
    <td class="desc">A toy</td>
</tr>

Is there any elegant way/function to convert this to Javascript associative array? 有什么优雅的方法/功能可以将其转换为Javascript关联数组吗? How to go about it? 怎么做呢?

$('tr').map(function(){
    return {
        cell: $('.cell', this).text(),
        desc: $('.desc', this).text()
    }
})

jQuery(Object { cell="Hello", desc="A word"}, Object { cell="Bye", desc="A word"}, Object { cell="Tricicle", desc="A toy"})

http://jsfiddle.net/cyFW5/ - here and it will works for every td with a class http://jsfiddle.net/cyFW5/-在这里,它将适用于具有类的每个td

$(function() {

    var arr = [],
        tmp;

    $('#Words tr').each(function() {

        tmp = {};

        $(this).children().each(function() {

            if ($(this).attr('class')) {
                tmp[$(this).attr('class')] = $(this).text();
            }

        });

        arr.push(tmp);
    });

    console.log(arr);

});​
var table = [];
$('table tr').each(function() {
    var row = [];
    $(this).find('td').each(function() {
        var cell = {};
        cell[$(this).attr('class')] = $(this).html();
        row.push(cell);
    });
    table.push(row);
});

Here's a demo , watch the console. 这是一个演示 ,观看控制台。

$(function() {

    var words = [];

    $('#Words tr').each(function() {
        words.push({
            cell: $('.cell', this).text(),
            desc: $('.desc', this).text()
        });
    });

    console.log(words);

});​

Given this specific use case then this would work: 给定此特定用例,则可以使用:

var results = {};
$('table#Words tr').each(function(i, x){
    results[i] = {
      desc: $(x).find('.desc').text(),
      cell: $(x).find('.cell').text()
    }
});

But why have the whole conversion to an object? 但是,为什么要全部转换为对象? What's it being used for, there might be an easier method of walking through the data. 它的用途是,可能会有一种更简单的遍历数据的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM