Tengo una función que recibe un objeto y una cadena. ¿Cómo puedo poner bien los valores de un objeto en una cadena?
const str = "/api/items/%id%/%name%";
let obj = { id : 20, name: 'John Dow'}; function path(obj, str){ let res = //some code return res }
la función debería devolver "/api/items/20/John%20Dow"
no llega a una buena solución. ayudame por favor
La siguiente función hará el truco:
const str = "/api/items/%id%/%name%"; let obj = { id : 20, name: 'John Dow'}; function path(obj, str){ for(const [key, value] of Object.entries(obj)) { str = str.replace(`%${key}%`, encodeURI(value)) } return str; } console.log(path(obj, str))
use template string
con el método encodeURI
let obj = { id : 20, name: 'John Dow'}; const apiItemsPath = ({id, name}) => `/api/items/${id}/${encodeURI(name)}` console.log(apiItemsPath(obj))
puedes usar :
const str = "/api/items/%id%/%name%"; let obj = { id: 20, name: 'John Dow' }; function path(obj, str) { let res = str; Object.keys(obj).forEach(key => { res = res.replace(`%${key}%`, encodeURI(obj[key])); }); return res; } console.log(path(obj, str));