1

In Javascript, if you serialize() a key/value array pair, then you'll get something like single=Single&multiple=Multiple. Is there any way to "unserialize" this string to get an array of key/value pairs again? If not, what's the most efficient way?

penu
  • 968
  • 1
  • 9
  • 22

1 Answers1

0

As answered here: https://stackoverflow.com/a/10126995/183181

var str = 'single=Single&multiple=Multiple';
console.log( getParams(str) );


function getParams (str) {
   var queryString = str || window.location.search || '';
   var keyValPairs = [];
   var params      = {};
   queryString     = queryString.replace(/.*?\?/,"");

   if (queryString.length)
   {
      keyValPairs = queryString.split('&');
      for (pairNum in keyValPairs)
      {
         var key = keyValPairs[pairNum].split('=')[0];
         if (!key.length) continue;
         if (typeof params[key] === 'undefined')
         params[key] = [];
         params[key].push(keyValPairs[pairNum].split('=')[1]);
      }
   }
   return params;
}
Community
  • 1
  • 1
vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • 1
    I think you should mark the question as a duplicate instead of reproducing the same answer. – trincot Apr 03 '17 at 23:54
  • @trincot I think you're right ;) Though, until it's determined how exactly he would expect the data to be formatted, I'll also leave this here – vol7ron Apr 03 '17 at 23:58