将 javascript 字典转换为要在 jquery.params 中传递的数组/对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5405527/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:05:37  来源:igfitidea点击:

Converting javascript dictionary to array/object to be passed in jquery.params

javascriptjqueryarraysdictionary

提问by TopCoder

I have a javascript variable which is a dictionary of key-values pairs of querystring. I need to again convert this dictionary into a query string. I am using jquery.param functin but it takes either an array or an object. How can I convert my dictinoary variable to array/object which jquery.params can accept.

我有一个 javascript 变量,它是查询字符串键值对的字典。我需要再次将此字典转换为查询字符串。我正在使用 jquery.param functin 但它需要一个数组或一个对象。如何将我的字典变量转换为 jquery.params 可以接受的数组/对象。

Tried using serializeArray but it does not work.

尝试使用 serializeArray 但它不起作用。

回答by Guffa

The jQuery.parammethod can take an array i in this form:

jQuery.param方法可以采用以下形式的数组 i:

[{ name: 'asdf', value: '42' },{ name: 'qwerty', value: '1337' }]

If your dictionary have other property names, you can use the jQuery.mapmethod to convert it. Example:

如果您的字典有其他属性名称,您可以使用该jQuery.map方法对其进行转换。例子:

arr = $.map(arr, function(e){
  return { name: e.key, value: e.val };
});

回答by Jordan Gray

If I understand your question right (some code samples would help!) by "dictionary" you mean a construction like:

如果我正确理解您的问题(一些代码示例会有所帮助!)“字典”,您的意思是这样的结构:

var dict = { key1: value1, key2: value2 … }

or:

或者:

var dict = {};
dict[key1] = value1;
dict[key2] = value2;

or possibly:

或者可能:

var dict = {};
dict.key1 = value1;
dict.key2 = value2;

If so, you should know that allof these are doing the same thing, i.e. setting properties on JavaScript objects, and should be serialised correctly by jQuery.param. Succinctly, JavaScript objects ≈ dictionaries.

如果是这样,您应该知道所有这些都在做同样的事情,即在 JavaScript 对象上设置属性,并且应该由jQuery.param. 简而言之,JavaScript 对象≈字典。