mirror of
https://github.com/Fechin/reference.git
synced 2026-11-20 21:23:11 +03:00
918 B
918 B
title, tags, layout
| title | tags | layout | ||||
|---|---|---|---|---|---|---|
| How to convert url parameters to object in JavaScript |
|
note |
In this Article we will go through how to convert url parameters to object only using single line of code in JavaScript.
This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.
Let's define this short function:
const getUrlParams = query => Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v}), {});
Example
getUrlParams(location.search); // Get the parameters of the current URL
getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }
// Duplicate key
getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }