Query-string encoding of a Javascript Object


The query string is made up of query parameters and used to send data to the server. This part of the URL is optional. It needs to be constructed by the developer. This can be done using a native method called encodeURIComponent.

The encodeURIComponent() function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character

Using the new ES6 format, objects can be query string encoded in the following way −

Example

let obj = {
   name: 'John',
   age: 25,
   city: 'Chicago'
};
let qs = Object.keys(obj)
            .map(k =>
`${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`) .join('&');
console.log(qs);

Output

This will give the output −

name=John&age=25&city=Chicago

Updated on: 27-Nov-2019

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements