Reputation: 5296
What's the best way to receive a sorted parameter query string from two JavaScript objects using querystring
, qs
, etc?
I am adding properties from obj2 to obj1:
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
obj1
ends up with a bunch of properties.
After I stringify
obj1
, I need all parameters in the query string to be alphabetically sorted by key:
a=v1&b=v2&c=v3
Upvotes: 0
Views: 4313
Reputation: 700650
As object properties can not be sorted (their order is unspecified), you would need to put them in an array.
You can make an object that handles a key-value pair:
function KeyValue(key, value) {
this.key = key;
this.value = value;
}
KeyValue.prototype = {
toString: function() {
return encodeURIComponent(this.key) + '=' + encodeURIComponent(this.value);
}
};
By creating an array of KeyValue
objects from the properties in the object, you can then sort them on the key, and just use join
to make the query string:
var obj1 = { x: '1 2 3', b: 42, f: 'x<y' };
var query = [];
for (var key in obj1) {
if (obj1.hasOwnProperty(key)) {
query.push(new KeyValue(key, obj1[key]));
}
}
query.sort(function(a, b){ return a.key < b.key ? -1 : 1 });
var queryString = query.join('&');
The variable queryString
now contains b=42&f=x%3Cy&x=1%202%203
.
Demo: http://jsfiddle.net/915wt4j4/
Upvotes: 4