Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

78
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda