2012-04-13 10 views
1

は、私はこのようなHTML、jQueryを使用して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> 

はJavascript連想配列にこれを変換する任意のエレガントな方法/機能がありますがあると?それについて移動する方法?

+1

Javascriptの連想配列オブジェクトのみと数値配列を持っていません(オブジェクト数字キー付き) Paystey

答えて

4
$('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"}) 
0

Here's a demo、コンソールを監視。この特定のユースケースを考えると

$(function() { 

    var words = []; 

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

    console.log(words); 

});​ 
0

、これは動作します:

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

しかし、なぜオブジェクトへの全体の変換がありますか?何が使われているのか、データを歩き回る簡単な方法があるかもしれません。

1

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); 

});​ 
1
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); 
}); 
関連する問題