0

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?

Joji
  • 4,703
  • 7
  • 41
  • 86
  • Are you sure this URL is correct? Shouldn't there be a `?` before the query part? If there were, you could simply use `Object.fromEntries(new URL(urlString).searchParams)` without the whole splitting and such. – CherryDT Oct 11 '21 at 19:12

2 Answers2

1
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

Lionel Rowe
  • 5,164
  • 1
  • 14
  • 27
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)
Spectric
  • 30,714
  • 6
  • 20
  • 43