Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten a javascript object to pass as querystring

I have a javascript object that I need to flatten into a string so that I can pass as querystring, how would I do that? i.e:

{ cost: 12345, insertBy: 'testUser' } would become cost=12345&insertBy=testUser

I can't use jQuery AJAX call for this call, I know we can use that and pass the object in as data but not in this case. Using jQuery to flatten to object would be okay though.

Thank you.

like image 768
Saxman Avatar asked Mar 31 '11 19:03

Saxman


People also ask

What is flatten object in JavaScript?

We make a function called flatten object which takes input of an object and returns an object. Loop through the object and check the type of the current property: If it is of type Object and it is not an Array , recursively call the function again. Otherwise, store the value in the result.

What is Querystring JavaScript?

A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.

Can you pass an object in JavaScript function?

Methods—setting functions as properties of objects. In JavaScript, you can use functions as values, just like numbers, strings, and objects. That means you can pass them as arguments, return them from other functions, and set them as properties of objects.


2 Answers

You want jQuery.param:

var str = $.param({ cost: 12345, insertBy: 'testUser' }); // "cost=12345&insertBy=testUser" 

Note that this is the function used internally by jQuery to serialize objects passed as the data argument.

like image 30
lonesomeday Avatar answered Oct 09 '22 23:10

lonesomeday


Here's a non-jQuery version:

function toQueryString(obj) {     var parts = [];     for (var i in obj) {         if (obj.hasOwnProperty(i)) {             parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));         }     }     return parts.join("&"); } 
like image 192
Tim Down Avatar answered Oct 09 '22 22:10

Tim Down