I have a function which receives an object and a string. How can I nicely put values from an object into a string
const str = "/api/items/%id%/%name%";
let obj = { id : 20, name: 'John Dow'};
function path(obj, str){
let res = //some code
return res
}
the function should return "/api/items/20/John%20Dow"
does not come up with a good solution. help me please
The following function will do the trick:
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
with encodeURI
method
let obj = { id : 20, name: 'John Dow'};
const apiItemsPath = ({id, name}) => `/api/items/${id}/${encodeURI(name)}`
console.log(apiItemsPath(obj))
you can use :
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));