0

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
4
  • JS objects are unordered. Commented Nov 16, 2014 at 12:23
  • Why would you need the query string parameters in any specific order? Commented Nov 16, 2014 at 12:24
  • @Scimonster I know. That's why the question. Commented Nov 16, 2014 at 12:27
  • @Guffa That's a requirement Commented Nov 16, 2014 at 12:27

1 Answer 1

4

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Beautiful. Thank you. I had to add var before key in for (key in obj1) { line in order for the code to work in a function
@kyrylkov: Ah, naturally. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.