Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Tried using serializeArray but it does not work.

like image 901
TopCoder Avatar asked Mar 23 '11 12:03

TopCoder


People also ask

How to convert an object{} into an array[] in JavaScript?

To convert an object to an array you use one of three methods: Object.keys() , Object.values() , and Object.entries() . Note that the Object.keys() method has been available since ECMAScript 2015 or ES6, and the Object.values() and Object.entries() have been available since ECMAScript 2017.

How to convert object values to array in JavaScript?

JavaScript Objects Convert object's values to array You can convert its values to an array by doing: var array = Object. keys(obj) . map(function(key) { return obj[key]; }); console.

How to convert an object to an array of key value pairs in JavaScript?

Approach: We will use Object. entries() which is available in JavaScript. Object. entries() method is used to return an array consisting of enumerable property [key, value] pairs of the object which are passed as the parameter.


2 Answers

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

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

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

arr = $.map(arr, function(e){
  return { name: e.key, value: e.val };
});
like image 153
Guffa Avatar answered Oct 05 '22 12:10

Guffa


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 all of 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.

like image 30
Jordan Gray Avatar answered Oct 05 '22 13:10

Jordan Gray