Created
February 3, 2019 20:02
-
-
Save mrroot5/d85b1c26e2bc85a51f3280cb5eb1de92 to your computer and use it in GitHub Desktop.
Añade parámetros query string a una URL desde un objeto JSON. Usable por fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function addParams(url = "", params = {}) { | |
// Inicializamos la URL | |
let myUrl = new URL(url); | |
// Obtenemos todas las keys de los parametros que nos vienen del objeto, en el ejemplo "foo" y "eggs" | |
// Usamos el foreach para recorrer cada key y extraer su valor con params[key] | |
// Con searchParams.append agregamos los parametro que queremos | |
Object.keys(params).forEach(key => openStreetMapReverseGeocodeUrl.searchParams.append(key, params[key])); | |
// Retornamos la url | |
return myUrl; | |
} | |
// Como usarlo | |
let urlWithParams = addParams('http://my.cool/url', {"foo": "bar", "eggs": "spam"}); | |
// El resultado es un objeto entendible por fetch | |
// La cadena resultante seria: | |
// http://my.cool/url?foo=bar&eggs=spam |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment