Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 and 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 Object.keys() and map()
Using ES6 features, objects can be query string encoded by combining Object.keys(), map(), and join() methods:
let obj = {
name: 'John',
age: 25,
city: 'Chicago'
};
let qs = Object.keys(obj)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`)
.join('&');
console.log(qs);
name=John&age=25&city=Chicago
Using URLSearchParams (Modern Approach)
The URLSearchParams API provides a cleaner way to build query strings:
let obj = {
name: 'John Doe',
age: 25,
city: 'New York'
};
let params = new URLSearchParams();
Object.keys(obj).forEach(key => {
params.append(key, obj[key]);
});
console.log(params.toString());
name=John+Doe&age=25&city=New+York
Handling Special Characters
Query string encoding automatically handles special characters that need escaping:
let obj = {
name: 'John & Jane',
email: 'user@example.com',
message: 'Hello World!'
};
let qs = Object.keys(obj)
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`)
.join('&');
console.log(qs);
name=John%20%26%20Jane&email=user%40example.com&message=Hello%20World!
Comparison
| Method | Browser Support | Advantages |
|---|---|---|
Object.keys() + map() |
All modern browsers | Flexible, customizable |
URLSearchParams |
Modern browsers (IE not supported) | Built-in, handles encoding automatically |
Conclusion
Both approaches effectively convert JavaScript objects to query strings. Use URLSearchParams for modern applications, or the manual approach for broader browser compatibility.
