How to Convert a JavaScript Object to a URL?
need to use an API to send a notification to a specific group of users (a room). To do this, I need to dynamically build a URL using parameters stored in a JavaScript object. For example, I have the following object:
var settings = { format: "json", auth_token: "exampleToken", room_id: 555, from: "Notification", message: "Hello" }
And I want to obtain the following URL:
https://api.example.com/v1/rooms/message?format=json&auth_token=exampleToken&room_id=555&from=Notification&message=Hello
How can I convert an object to a URL query string using JavaScript?
Answers
Tom Dupuis
7 months ago
1 comment
Rating
Hi! If you're working with ES6, you can do this using Object.entries():
This will create the string:
Viktor Eriksson
7 months ago
Rating
Thank you! Based on your answer, I assembled my own code in pure JavaScript, as I wanted, without using external libraries:
Result achieved! Here it is:
Paul Lefevre
7 months ago
1 comment
Rating
You can use jQuery and the jQuery.param function to achieve this:
This will produce the URL:
Viktor Eriksson
7 months ago
Rating
Thank you for the answer.
However, I would prefer not to use additional libraries for this solution.