25

I need to make a Javascript array from URL, eg:

turn this:

http://maps.google.com/maps/api/staticmap?center=Baker Street 221b, London&size=450x450&markers=Baker Street 221b, London&sensor=false

Into something like:

array['center'] = Baker Street 221b, London
array['size'] = 450x450
// and so on...

I need to make this serializaion/unserialization work both ways (url to array and array to the part of the url). Are there some built-in functions that do this?

Thanks in advance!

skazhy
  • 3,811
  • 7
  • 26
  • 29
  • Possible duplicate: http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript This other question does not discuss serialization (only deserialization). – strager Nov 28 '10 at 16:32
  • 1
    That's not really an **array**, it's an **object** with properties. The notation is correct but the terminology is off, in other words. – Pointy Nov 28 '10 at 16:44
  • 1
    @Pointy: True, but I actually think "(associative) array" is more readable than "object" and gets the point across. – casablanca Nov 28 '10 at 16:46
  • 1
    @casablanca I don't disagree, but the question explicitly says, "JavaScript array", but what's described really shouldn't be an Array instance. – Pointy Nov 28 '10 at 16:52

4 Answers4

50

URL to array: (adapted from my answer here)

function URLToArray(url) {
    var request = {};
    var pairs = url.substring(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < pairs.length; i++) {
        if(!pairs[i])
            continue;
        var pair = pairs[i].split('=');
        request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
     }
     return request;
}

Array to URL:

function ArrayToURL(array) {
  var pairs = [];
  for (var key in array)
    if (array.hasOwnProperty(key))

      pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(array[key]));
  return pairs.join('&');
}
Community
  • 1
  • 1
casablanca
  • 66,266
  • 7
  • 126
  • 145
  • I don't need to parse the location but a variable containing the URL. I tried running it (with location replaced with variable name) and it "hangs" on this line var pairs = location.search.substring(1).split('&'); – skazhy Nov 28 '10 at 17:12
  • @skazhy: I've edited the function to accept a parameter instead. – casablanca Nov 28 '10 at 17:13
  • Thank you for this solution, it worked perfect for what I needed [Only needed 1st function]. I was going to use URI.js with jQuery, but this is a much simpler, eloquent, solution. – Matt Sep 28 '13 at 18:12
  • nice functions butURLToArray is not working if you have in your url string smth like elem[]=23&elem[]=55; – alex toader Nov 18 '13 at 11:09
  • Thanks! This works great. However, if you give it a URL without parameters, it returns the URL in the object: `{http://example.com: "undefined"}`. I modified it slightly to return undefined: `var qIndex = url.indexOf('?'); if(qIndex == -1){ return undefined; } var pairs = url.substring(qIndex + 1).split('&');` – Dan Leveille Jan 24 '17 at 23:02
3

the above function URLToArray is not working when url string has elem[]=23&elem[]=56.. see below the adapted function... hope it is working - not 100% tested

function URLToArray(url) {
        var request = {};
        var arr = [];
        var pairs = url.substring(url.indexOf('?') + 1).split('&');
        for (var i = 0; i < pairs.length; i++) {
          var pair = pairs[i].split('=');

          //check we have an array here - add array numeric indexes so the key elem[] is not identical.
          if(endsWith(decodeURIComponent(pair[0]), '[]') ) {
              var arrName = decodeURIComponent(pair[0]).substring(0, decodeURIComponent(pair[0]).length - 2);
              if(!(arrName in arr)) {
                  arr.push(arrName);
                  arr[arrName] = [];
              }

              arr[arrName].push(decodeURIComponent(pair[1]));
              request[arrName] = arr[arrName];
          } else {
            request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
          }
        }
        return request;
    }

where endWith is taken from here

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
Community
  • 1
  • 1
alex toader
  • 1,813
  • 1
  • 14
  • 14
0
 /**
 * (C)VIOLONIX inc.
 * Parser for make multidim array from
 * foo[]=any&foo[]=boy, or foo[0][kids]=any&foo[1][kids]=boy
 * result: foo=[[any],[boy]] or foo=[kids:[any],kids:[boy]]
 */    

 var URLToArray = function(url){
        function parse_mdim(name, val, data){
            let params = name.match(/(\[\])|(\[.+?\])/g);
            if(!params)params = new Array();
            let tg_id = name.split('[')[0];


            if(!(tg_id in data)) data[tg_id] = [];
            var prev_data = data[tg_id];

            for(var i=0;i<params.length;i++){
                if(params[i]!='[]'){
                    let tparam = params[i].match(/\[(.+)\]/i)[1];
                    if(!(tparam in prev_data)) prev_data[tparam] = [];
                    prev_data = prev_data[tparam];
                }else{
                    prev_data.push([]);
                    prev_data = prev_data[prev_data.length-1];
                }

            }
            prev_data.push(val);

        }


        var request = {};
        var arr = [];
        var pairs = url.substring(url.indexOf('?') + 1).split('&');

        for (var i = 0; i < pairs.length; i++) {
           var pair = pairs[i].split('=');
           if(decodeURIComponent(pair[0]).indexOf('[')!=-1)
               parse_mdim(decodeURIComponent(pair[0]), decodeURIComponent(pair[1]), request);
           else 
               request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
         }

        //To-do here check array and simplifity it: if parameter end with one index in array replace it by value [0]    

         return request;

    }
SEN
  • 1
-2

There's the query-object jQuery plugin for that

Eric
  • 87,154
  • 48
  • 211
  • 332