5

When looking at location.search, what's the best way to take the query parameters and turn them into an object literal? Say I've got a URL that looks like this:

http://foo.com?nodeId=2&userId=3&sortOrder=name&sequence=asc

What I'd like to wind up with is an object literal that looks like this:

var params = {
 nodeId : 2,
 userId : 3,
 sortOrder: name,
 sequence: asc
}

So I'd like to do something like this:

var url = location.search;
url = url.replace('?', '');
var queries = url.split('&');
var params = {};
for(var q in queries) {
var param = queries[q].split('=');
params.param[0] = param[1];

};

But this line:

params.param[0] = param[1]

generates an error. How do you iterate through those keys if you don't know the key names?

We're using jQuery, and I'm sure there's a plugin to do this, but I'd like to understand how to program this anyway.

asked Jul 21, 2009 at 19:05

2 Answers 2

3

You should use

params[ param[0] ] = param[1]

FYI, you could use a regex approach too.

answered Jul 21, 2009 at 19:06

Comments

1

Try the URL Utils jQuery plugin, it does precisely this!

var params = $.queryString();

answered Jul 21, 2009 at 21:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.