使用点表示法jQuery查询字符串的对象数组

时间:2017-12-05 15:17:22

标签: javascript jquery

我正在使用$.param()函数将对象转换为查询字符串。但是我得到了一个像这样的对象:

{
   myArray: [{
      prop1: "somevalue"
   }, {
      prop1: "somevalue"
   }],
   someOtherProp: ...
}

传递此类对象时$.param的结果如下所示:

myArray[0][prop1]=somevalue&myArray[1][prop1]=somevalue&someOtherProp=...

但是,我想用点表示法对对象进行编码,如下所示:

myArray[0].prop1=somevalue&myArray[1].prop1=somevalue&someOtherProp=...

它并不一定要与jquery一起使用。其他解决方案也是可以接受的。

关于如何实现它的任何想法?谢谢!

2 个答案:

答案 0 :(得分:1)

您可以修改$ .param()中返回的字符串,使其适合所需的格式。

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

var params = $.param(yourObject);
params = params.replaceAll('%5D%5B', '].');
params = params.replaceAll('%5D', '');
params = params.replaceAll('%5B', '[');

答案 1 :(得分:-1)

如果您愿意稍微扩展jQuery

请参阅以下代码,该代码取自gist

似乎如果你想使用param,没有简单的方法可以做到这一点

带点符号支持的jQuery查询参数序列化

var r20 = /%20/g,
    rbracket = /\[\]$/,
    rCRLF = /\r?\n/g,
    rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
    rsubmittable = /^(?:input|select|textarea|keygen)/i,
    rIdentifier = /^[$A-Z_][0-9A-Z_$]*$/i;

jQuery.fn.extend({
    serialize: function() {
        return jQuery.param( this.serializeArray() );
    },
    serializeArray: function() {
        return this.map(function(){
            // Can add propHook for "elements" to filter or add form elements
            var elements = jQuery.prop( this, "elements" );
            return elements ? jQuery.makeArray( elements ) : this;
        })
        .filter(function(){
            var type = this.type;
            // Use .is(":disabled") so that fieldset[disabled] works
            return this.name && !jQuery( this ).is( ":disabled" ) &&
                rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
                ( this.checked || !manipulation_rcheckableType.test( type ) );
        })
        .map(function( i, elem ){
            var val = jQuery( this ).val();

            return val == null ?
                null :
                jQuery.isArray( val ) ?
                    jQuery.map( val, function( val ){
                        return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
                    }) :
                    { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
        }).get();
    }
});

//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional, dotNotation ) {
    var prefix,
        s = [],
        add = function( key, value ) {
            // If value is a function, invoke it and return its value
            value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
            s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
        };

    // Set traditional to true for jQuery <= 1.3.2 behavior.
    if ( traditional === undefined ) {
        traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
    }
    if ( dotNotation === undefined ) {
        dotNotation = jQuery.ajaxSettings && jQuery.ajaxSettings.dotNotation;
    }

    // If an array was passed in, assume that it is an array of form elements.
    if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
        // Serialize the form elements
        jQuery.each( a, function() {
            add( this.name, this.value );
        });

    } else {
        // If traditional, encode the "old" way (the way 1.3.2 or older
        // did it), otherwise encode params recursively.
        for ( prefix in a ) {
            buildParams( prefix, a[ prefix ], traditional, dotNotation, add );
        }
    }

    // Return the resulting serialization
    return s.join( "&" ).replace( r20, "+" );
};

function buildParams( prefix, obj, traditional, dotNotation, add ) {
    var name;

    if ( jQuery.isArray( obj ) ) {
        // Serialize array item.
        jQuery.each( obj, function( i, v ) {
            if ( traditional || rbracket.test( prefix ) ) {
                // Treat each array item as a scalar.
                add( prefix, v );

            } else {
                // Item is non-scalar (array or object), encode its numeric index.
                buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, dotNotation, add );
            }
        });

    } else if ( !traditional && jQuery.type( obj ) === "object" ) {
        // Serialize object item.
        for ( name in obj ) {
            if( dotNotation && rIdentifier.test(name) ) {
                buildParams( prefix + '.' + name, obj[name], traditional, dotNotation, add )
            } else {
                buildParams( prefix + "[" + name + "]", obj[ name ], traditional, dotNotation, add );
            }
        }

    } else {
        // Serialize scalar item.
        add( prefix, obj );
    }
}