Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

77
Views
Get array of objects from URLSearchParams

I need to extract filter which is an array of objects from a URL string:

http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u.

This is currently what I have:

  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const filterParamsValue = searchParams.getAll('filter'); // returns []

This is what I want to get from the filter:

[ { id: 'MenuID', value: '2' }, { id: 'ParentMenuName', value: 'u' } ]
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Some quick functioning :D ...

let s = `http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u`

// get just array of strings like ['filter[0][id]=MenuID', ...]
let arr = s.split(/\&/).slice(1)
let filters = {}

arr.forEach(f => {
    const id = f.match(/\[([\d]+)\]/)[1]
    const prop = f.match(/\[([a-z]+)\]/)[1]

    if(filters[id]) {
        filters[id][prop] = f.match(/=([\w]+)/)[1]
    } else {
        filters[id] = {}
        filters[id][prop] = f.match(/=([\w]+)/)[1]
    }
})


// show filters object:
console.dir( filters )

/*

  { 
    0: { id: "MenuID", value: "2"},
    1: { id: "ParentMenuName", value: "u"}
  }

*/

This gives you Object of filters. If you need an array, you may convert it as:

/**
 * get object of filters and make an array of filters 
 */
const arrayOfFilters = []

for(key in filters) {
    arrayOfFilters.push(filters[key])
}

console.log(arrayOfFilters)
about 4 years ago · Juan Pablo Isaza Report

0

I wrote a prototype function to parse square brackets array of objects. This function is dynamically parse brackets, that is good for nested objects

URLSearchParams.prototype.toObject = function () {
    let _obj = {};
    const bracketToDots = function (str) {
        return str.replaceAll('[', '.').replaceAll(']', '')
    }
    const parseDotNotation = function (str, val, obj) {
        let currentObj = obj,
            keys = str.split("."),
            i, l = Math.max(1, keys.length - 1),
            key;

        if (l === 1) {
            key = keys[0];
            currentObj[key] = val;
        } else {
            for (i = 0; i < l; ++i) {
                key = keys[i];
                currentObj[key] = currentObj[key] || {};
                currentObj = currentObj[key];
            }

            currentObj[keys[i]] = val;
        }
    }
    for (const [key, value] of this.entries()) {
        parseDotNotation(bracketToDots(key), value, _obj);
    }
    return _obj;
}

const lo = new URL('http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u');
const searchParams = new URLSearchParams(lo.search);
const params = searchParams.toObject();

console.log(params['filter'])

Result:

{
  "0": {
    "id": "MenuID",
    "value": "2"
  },
  "1": {
    "id": "ParentMenuName",
    "value": "u"
  }
}
about 4 years ago · Juan Pablo Isaza Report

0

A short version

function getSearchParameters () {
    const url = new URL(window.location)
    const searchParams = new URLSearchParams(url.search)
    const paramObj = {}
    for (const key of searchParams.keys()) {
        paramObj[key] = searchParams.getAll(key).length > 1
            ? searchParams.getAll(key)
            : searchParams.get(key)
    }
    return paramObj
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!