Convert a JavaScript object to queryparams string
Emmanuel Gautier / May 16, 2022
1 min read
Converting a JS object to parameters in a URL is a common task for web developers but there are different ways to do it in depending on the context. Let's see two options depending whether your code is running in a browser or on a NodeJS server.
Browser Side Using URLSearchParams API
The URLSearchParams interface is available in the browser. It is used to manipulate the query string of a URL. This API is compatible with all modern browsers including the latest browser versions and excluding Internet Explorer.
Here is an example:
const params = {
name: 'John',
age: 30,
}
const qs = new URLSearchParams(params)
console.log(qs.toString())
If you are in the case you need to support Internet Explorer 11 or lower, you can use a URLSearchParams polyfill or the querystringify npm package.
Server Side Using querystring
The querystring module is part of NodeJS built-in modules. It is used to manipulate the query string of a URL as well.
Here is an example:
const querystring = require('querystring')
const params = {
name: 'John',
age: 30,
}
const qs = querystring.stringify(params)
console.log(qs)
Consulting
If you're seeking solutions to a problem or need expert advice, I'm here to help! Don't hesitate to book a call with me for a consulting session. Let's discuss your situation and find the best solution together.
Related Posts
Read Package.json file from Node.JS module
When you write a program you may want to read the content of the package.json file like what is the current package version. Here is one very simple way to read the content of this file.
Import a JSON file content from a Node.JS module
With the new Node.JS module it is possible to read the content of a JSON file with the import function but there is the right way to do it.
Configure yarn version for Cloudflare page build
With the new Cloudflare page build system, yarn package manager version can be more than version 1. But we can keep yarn version 1 configuring the build system with a package.json property.
Featured Posts
How to deal with Docker Hub rate limit on AWS
Since 2020, DockerHub has been limited to only 200 container image pull requests per six hours. This article will help you to deal with this limitation on AWS.
How to enable Python type checking in VSCode
Python now has support for type hints. In this article, we will see how to enable better IntelliSense and type checking analysis in VSCode.
How to manage Internationalization with NextJS SSG
Staticaly generating a website with the NextJS framework in different languages is not so obvious.