如何序列化JavaScript关联数组?

Fab*_*ora 2 javascript forms arrays jquery

我需要序列化一个关联的JavaScript数组.它是一种简单的产品形式和数值,但在构建数组之后似乎是空的.

代码在这里:http://jsbin.com/usupi6/4/edit

Fel*_*ing 6

通常,不要将JS数组用于"关联数组".使用普通对象:

var array_products = {};
Run Code Online (Sandbox Code Playgroud)

这就是为什么$.each不起作用:jQuery认识到你传递一个数组并且只是迭代数值属性.所有其他人都将被忽略.

数组应该只包含带数字键的条目.您可以指定字符串键,但很多功能都不会将它们考虑在内.


更好:

当您使用jQuery时,可以使用jQuery.param [docs]进行序列化.您只需构造正确的输入数组:

var array_products = []; // now we need an array again
$( '.check_product:checked' ).each(function( i, obj ) {
    // index and value
    var num = $(obj).next().val();
    var label = $(obj).next().next().attr( 'data-label' );
    // build array
    if( ( num > 0 ) && ( typeof num !== undefined ) ) {
        array_products.push({name: label, value: num});
    }      
});

var serialized_products = $.param(array_products);
Run Code Online (Sandbox Code Playgroud)

无需实现自己的URI编码功能.

DEMO


最好:

如果您给输入字段一个正确的name:

<input name="sky_blue" class="percent_product" type="text" value="20" />
Run Code Online (Sandbox Code Playgroud)

你甚至可以使用.serialize() [docs]并大大减少代码量(我使用下一个相邻的选择器[docs]):

var serialized_products = $('.check_product:checked + input').serialize();
Run Code Online (Sandbox Code Playgroud)

(它将包括0值).

DEMO


ale*_*lex 5

您可以使用JSON库(或本机JSON对象,如果可用)将其序列化.

var serialised = JSON.stringify(obj);
Run Code Online (Sandbox Code Playgroud)