0

Trying to learn something new here, and that is how to build an array from a query string using js or jquery. So lets say I have a URL that looks like this:

http://demo.dev.activemls.com/property/search?city=TOLEDO&bdrms=3&bthrms=2.0&lowprice=115000&highprice=125000&zip=&order=B&pagesize=30

assuming the query may not always have the same keys/values (the string could be longer or shorter), how would i then convert this string to an array like this:

var query = {
    city: "TOLEDO", 
    bdrms: 3,
    bthrms: 2.0,
    lowprice: 115000,
    highprice: 125000,
    zip: "",
    order: "B",
    pagesize: 30
};
3
  • That's not an array, it's an object. Commented Sep 12, 2015 at 15:03
  • sorry like I said, I am learning Commented Sep 12, 2015 at 15:03
  • @Barmar thank you for posting that link Commented Sep 12, 2015 at 15:13

1 Answer 1

2

Try utilizing String.prototype.split() , Array.prototype.splice() , do.. while loop

var str = "http://demo.dev.activemls.com/property/search?city=TOLEDO&bdrms=3&bthrms=2.0&lowprice=115000&highprice=125000&zip=&order=B&pagesize=30";

var arr = str.split(/\?|&|=/).splice(1);

var obj = {};

do {
  obj[arr.splice(0, 1)] = arr.splice(0, 1)[0]
} while(!!arr.length);

document.getElementsByTagName("pre")[0].textContent = JSON.stringify(obj, null, 2)
<pre></pre>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.