0

I have this URL:

http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000

Now I'm trying to encode the URL to an Object. This is my current attempt:

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;
}

However I need this function to return the array as a JSON array, and not the way it currently does:

Screenshot of object

How do I get my function to return my object array?

Leonard Niehaus
  • 500
  • 6
  • 16
  • Can you show your own code attempt and not the copy/paste job in place presently from this SO link https://stackoverflow.com/questions/4297765/make-a-javascript-array-from-url – GetSet Feb 15 '20 at 15:12
  • Does this answer your question? [How can I get query string values in JavaScript?](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – segFault Feb 15 '20 at 16:07

1 Answers1

1

You could first get the object with help from this question.

Example using URLSearchParams with a regular expression loop:

const url = "http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000";

const regex = /^([a-z0-9]+)?\[([a-zA-Z0-9]+)\]*/mi;

function URLToArray(url) {
 url = decodeURIComponent(url);
  const args = new URLSearchParams(url.split('?')[1]);
  
  let request = {};
  args.forEach((value, key) => {
   let baseKey = key;
    let ogValue = value;
    let lastKey = '';
   while ((m = regex.exec(key)) !== null) {
     if (m[1]) {
       baseKey = m[1];
        value = request[baseKey] || {};
       request[baseKey] = value;
      }
      
      if (m[2]) {
       value = value[lastKey] || value;
        value[m[2]] = value[m[2]] || {};
       lastKey = m[2];
      }
      
      key = key.replace(m[0], '');
    }
    
    if (lastKey) {
     value[lastKey] = ogValue;
    } else {
     request[baseKey] = value;
    }
  });
  return request;
}

console.log(URLToArray(url));

This isn't perfect you will be left with nested objects as opposed to proper arrays for your items, and there are likely libraries that can achieve the same result better.

segFault
  • 3,887
  • 1
  • 19
  • 31