Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

270
Visualizações
JavaScript: Is there a better way to construct an object from query strings of a url

I have a url string like this "http://url.com/foo/aa=342&bb=66" and I need to construct an object from it

{ aa: '342', bb: '66' }

Here is my attempt

function constructFromUrl(url) {
    return url.split('/').at(-1).split('&').reduce((accu, curr) => {
        const [key, value] = curr.split('=')
        accu[key] = value
        return accu
    },{})
}

It works ok but I feel like it is really brittle. Is there any better way of handling this?

Also, I am really bad at naming things - is there a better name for such a function?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

const getQueryParams = (urlStr) => Object.fromEntries([
    ...new URL(urlStr).searchParams
])

Note however that this will fail for your example URL string, because it's malformed — the query string must be separated with a ?, like this:

http://url.com/foo/?aa=342&bb=66

about 4 years ago · Juan Pablo Isaza Relatório

0

You can parse the parameters with the URLSearchParams constructor, then use Object.fromEntries:

const url = "http://url.com/foo/aa=342&bb=66"
const params = url.split("/").slice(-1)[0]
const result = Object.fromEntries(new URLSearchParams(params))

console.log('params:', params)
console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda