0

すべてのテーブルをループし、値thに基づいて配列を構築する次の関数を取得しました。selectors

出力は、サブオブジェクトを値として含む数値配列です。

配列を作成できるようになりまし.get()たが、これを連想配列に設定する方法がわかりません。

質問:最初のテーブル セル値を連想配列インデックスとして追加するにはどうすればよいですか?

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

ありがとう!

4

2 に答える 2

0

最後に、ソリューションはそれほど難しくありませんでした。代わりに使用し、.each()代わりに.map()出力に割り当てます。object[ final_index ].get()

于 2012-05-24T12:14:48.467 に答える
0

JavaScript には連想配列はありません。オブジェクトを使用するだけです:

var myObject = new Object();

次に、そのオブジェクトで数値または文字列を使用できます。

myObject = { 'foo' : 'bar' }

お役に立てれば :)

于 2012-05-19T15:55:52.977 に答える