Convert URL searchParams to plain JS Object
06 Feb 2021 - Help improve this postIn Node.js the url.parse
API is deprecated. But one of the great things was getting an plain JavaScript object from your query params:
const { query } = url.parse("https://example.com/?search=term&page=1", true);
console.log(query); // [Object: null prototype] { search: 'term', page: '1' }
Want to know what
[Object: null prototype]
is? Check this StackOverflow answer.
Fortunately this is also possible with the WHATWG URL API (new URL
).
const { searchParams } = new URL("https://example.com/?search=term&page=1");
const query = Object.fromEntries(searchParams);
console.log(query); // { search: 'term', page: '1' }
WHATWG URL API combined with Object.fromEntries
really helps here.
Happy coding! – Found a mistake or a typo? Please submit a PR to my GitHub-repo.