Query-string encoding of a Javascript Object

JavascriptFront End TechnologyObject Oriented Programming

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 −


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


This will give the output −

Published on 27-Nov-2019 14:46:11