简体   繁体   中英

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

Suppose I have HTML like this,

<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? 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

$(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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