2012-05-19 60 views
0

我得到以下函數,循環遍歷所有表th s,並根據selectors值構建一個數組。如何通過.get()爲jQuery數組設置關聯索引?

輸出是一個數值數組,其中包含子對象作爲值。

現在.get()允許我構建數組,但我無法找到如何將其設置爲關聯數組。

問題:如何將第一個表格單元格值添加爲assoc數組索引?

(function($) 
{ 
    $.fn.loadTableData = function(selectors) 
    { 
     var id = $(this).attr('id'); 

     /** 
     * Get the output array keys from the <thead/tfoot> cell/th #ids 
     */ 
     var columns = $('#' + id + ' table th').map(function($) 
     { 
      // This assumes that your headings are suitable to be used as 
      // JavaScript object keys. If the headings contain characters 
      // that would be invalid, such as spaces or dashes, you should 
      // use a regex here to strip those characters out. 
      return jQuery(this).attr('id'); 
     }); 

     /** 
     * Get the cell data, based on the selector object values by index 
     * @return row 
     */ 
     var cell_data = $('#' + id + ' table tr').map(function(index) 
     { 
      var row = {}; 

      // Skip empty rows (example: <thead/tfoot>) 
      if (0 === $(this).find('td').length) 
       return; 

      // Find all of the table cells on this row. 
      $(this).find('td').each(function(index, value) 
      { 
       // Skip empty keys 
       if (undefined == selectors[ index ]) 
        return; 

       // Determine the cell's column name by comparing its index 
       // within the row with the columns list we built previously. 
       var row_name = columns[ index ]; 

       // Add a new property to the row object, using this cell's 
       // column name as the key and the cell's text as the value. 
       if ('text' === selectors[ index ]) 
       { 
        row[ row_name ] = $(this).text(); 
       } 
       else 
       { 
        row[ row_name ] = $(this).find(selectors[ index ]).val(); 
       } 
      }); 

      // Finally, return the row's object representation, to be included 
      // in the array that $.map() ultimately returns. 
      return row; 

      // Don't forget .get() to convert the $ set to a regular array. 
     }).get(); 

     return cell_data; 
    }; 
})(jQuery); 

謝謝!

回答

0

的解決方案是不是很難在最後:使用.each()代替.map(),然後將其分配給輸出object[ final_index ]而不是使用.get()

0

JavaScript中沒有關聯數組。只需使用一個對象:

var myObject = new Object(); 

然後你可以使用數字或字符串在該對象:

myObject = { 'foo' : 'bar' } 

希望這有助於:)

+0

嗯,好的..那不回答我的問題... – kaiser

+0

爲什麼不呢?你想要一個assoc數組,如這個數組('foo'=>'bar'),但在JavaScript中是正確的?那麼,唯一的方法就是使用一個對象,如{'foo':'bar'}。你能改述一下你的問題嗎,讓我更好理解? –

+0

好的。我知道'array'和'object'的區別。 :)目前我使用'.get()'來構建數組('@see cell_data')。你將如何改變上面的↑代碼來獲得一個具有命名鍵而不是數組的對象? – kaiser