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

  • Gravatar — онлайн-сервис, позволяющий пользователям Интернета поддерживать постоянную картинку на большинстве сайтов.

    Viktor Eriksson

    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

  • Gravatar — онлайн-сервис, позволяющий пользователям Интернета поддерживать постоянную картинку на большинстве сайтов.

    Viktor Eriksson

    Thank you for the answer.
    However, I would prefer not to use additional libraries for this solution.

  • Gravatar — онлайн-сервис, позволяющий пользователям Интернета поддерживать постоянную картинку на большинстве сайтов.

    Tom Dupuis

    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

  • Gravatar — онлайн-сервис, позволяющий пользователям Интернета поддерживать постоянную картинку на большинстве сайтов.

    Paul Lefevre

    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