如何序列化 JavaScript 关联数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6438596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to serialize a JavaScript associative array?
提问by Fabio Mora
I need to serialize an associative JavaScript array. It's a simple form of products and a numeric values, but just after building the array seems empty.
我需要序列化一个关联的 JavaScript 数组。它是一种简单的乘积和数值形式,但在构建数组之后似乎是空的。
The code is here: http://jsbin.com/usupi6/4/edit
代码在这里:http: //jsbin.com/usupi6/4/edit
回答by Felix Kling
In general, don't use JS arrays for "associative arrays". Use plain objects:
一般来说,不要将 JS 数组用于“关联数组”。使用普通对象:
var array_products = {};
That is why $.each
does not work: jQuery recognizes that you pass an arrayand is only iterating over numericalproperties. All others will be ignored.
这就是$.each
行不通的原因:jQuery 识别出您传递了一个数组,并且仅迭代数字属性。所有其他人都将被忽略。
An array is supposed to have only entries with numerical keys. You can assign string keys, but a lot of functions will not take them into account.
数组应该只有带有数字键的条目。您可以分配字符串键,但很多功能不会考虑它们。
Better:
更好的:
As you use jQuery, you can use jQuery.param
[docs]for serialization. You just have to construct the proper input array:
当您使用 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);
No need to implement your own URI encoding function.
无需实现自己的 URI 编码功能。
Best:
最好的事物:
If you give the input fields a proper name
:
如果你给输入字段一个适当的name
:
<input name="sky_blue" class="percent_product" type="text" value="20" />
you can even make use of .serialize()
[docs]and greatly reduce the amount of code (I use the next adjacent selector [docs]):
您甚至可以使用.serialize()
[docs]并大大减少代码量(我使用下一个相邻的选择器[docs]):
var serialized_products = $('.check_product:checked + input').serialize();
(it will include 0
values though).
(0
虽然它会包括值)。
回答by alex
You could serialise it with a JSON library(or the native JSON objectif available).
您可以使用JSON 库(或本机JSON 对象,如果可用)对其进行序列化。
var serialised = JSON.stringify(obj);