Vivek
Vivek

Reputation: 13238

Get the array of objects from query parameters in javascript

I'm trying to parse the array from the url query parameters. The url is as below which contains the array of emp objects specified in query parameters

http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom

Can someone please help me with the function that will parse such query params(with some ReGEX maybe) and returns the array as below

[{id:'21',name:'john'},{id:'22',name:'tom'}]

Note: There could be any number of emp objects mentioned in the query params, for example purpose I've just added two. I've looked for similar solutions but none of them seems to return the array which has its objects specified in the query params with the index value. So please don't mark the question as duplicate

Edit: I've written the below function which works for fetching simple query params but doesn't work for array of objects specified in query param as above.

export const getQueryParamByName = (name, url) => {
    if (!url) url = window.location.href;
    name = name.replace(/[[\]]/g, '\\$&');
    const regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
    const results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

Upvotes: 0

Views: 3095

Answers (3)

Rajneesh
Rajneesh

Reputation: 5308

I'll share my try:

var url = `http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom`;
var data = url.split('?')[1].split('&');

var result = Object.values(data.reduce((acc, elem)=>{
   key = elem.match(/\d+/)[0];
   kv = elem.split(".")[1].split('=');
   acc[key] = {...(acc[key] || []), ...{[kv[0]]:kv[1]}}
   return acc;
},{}));

console.log(result);

Upvotes: 1

Paolo Carrara
Paolo Carrara

Reputation: 394

I tried to create a generic function to handle the layed problem:

var url = '?person[0].name=Jack&person[0].id=1&person[1].name=Jonathan&note=book';

function removeFirstChar (string) {
  var tmp = string.split('');
  tmp.splice(0 , 1); 
  return tmp.join('');
}

function parse (url) {
  url = removeFirstChar(url);
  var queryParamsArray = url.split('&');

  var object = {};
  for (var i = 0; i < queryParamsArray.length; i++) {
    var queryParamArray = queryParamsArray[i].split('=');
    var re = /\[(\d*)\]/;

    if (re.test(queryParamArray[0])) {
      var reString = /\w+/g;
      var base = (((queryParamArray[0].split('.'))[0]).match(reString))[0];
      var property = (queryParamArray[0].split('.'))[1];

      if (!object[base]) {
        object[base] = [];
      }

      const urlParts = re.exec(queryParamArray[0]);
      const index = urlParts[1];

      if (object[base][index]) {
        object[base][index][property] = queryParamArray[1];
      } else {
        object[base][index] = {
          [property]: queryParamArray[1]
        }
      }
    } else {
      object[queryParamArray[0]] = queryParamArray[1];
    }
  }

  return object;
}

It will create an object with all the properties from the query string, the example query string provided will generate the following object:

{
    person: [
        {
            name: 'Jack',
            id: '1'
        },
        {
            name: 'Jonathan'
        }
    ],
    note: 'book'
}

Upvotes: 0

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

You may match id and name pair with the following regex:

(emp\[\d+]\.)id=(\d+)&\1name=([^&]+)

(demo)

and then iterate through all such matches returned by matchAll() to build the array of id-name objects:

const extractObjects = url => {
  const regex = /(emp\[\d+]\.)id=(\d+)&\1name=([^&]+)/g;
  const result = [];
  for (const match of url.matchAll(regex)) {
    result.push({id: match[2], name: match[3]});
  }
  return result;
}

const url = 'http://localhost:8080/list?emp[0].id=21&emp[0].name=john&emp[1].id=22&emp[1].name=tom';
const objects = extractObjects(url);
console.log(objects);

Upvotes: 0

Related Questions