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?

Viktor Eriksson

7 months ago

4 answers

84 views

Rating

06
Answer

Answers

Tom Dupuis

7 months ago

1 comment

Rating

00

Hi! If you're working with ES6, you can do this using Object.entries():

		
Object.entries(settings) .map(([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`) .join("&");

This will create the string:

		
format=json&auth_token=exampleToken&room_id=555&from=Notification&message=Hello

Reply

    Viktor Eriksson

    7 months ago

    Rating

    01

    Thank you! Based on your answer, I assembled my own code in pure JavaScript, as I wanted, without using external libraries:

    		
    var settings = { format: "json", auth_token: "exampleToken", room_id: 555, from: "Notification", message: "Hello" }; var urlParams = Object.keys(settings) .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(settings[key])}`) .join('&'); var apiUrl = "https://api.example.com/v1/rooms/message?" + urlParams; console.log(apiUrl);

    Result achieved! Here it is:

    		
    https://api.example.com/v1/rooms/message?format=json&auth_token=exampleToken&room_id=555&from=Notification&message=Hello

    Reply

Paul Lefevre

7 months ago

1 comment

Rating

00

You can use jQuery and the jQuery.param function to achieve this:

		
var settings = { format: "json", auth_token: "exampleToken", room_id: 555, from: "Notification", message: "Hello" }; var urlParams = jQuery.param(settings); var apiUrl = "https://api.example.com/v1/rooms/message?" + urlParams; console.log(apiUrl);

This will produce the URL:

		
https://api.example.com/v1/rooms/message?format=json&auth_token=exampleToken&room_id=555&from=Notification&message=Hello

Reply

    Viktor Eriksson

    7 months ago

    Rating

    01

    Thank you for the answer.

    However, I would prefer not to use additional libraries for this solution.

    Reply