Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

42
Vistas
Iinsert values into url

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

7 months ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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))
7 months ago · Juan Pablo Isaza Denunciar

0

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))
 

7 months ago · Juan Pablo Isaza Denunciar

0

you can use :

  • Object.keys to iterate on object property
  • string.replace to replace element in your string
  • encodeUri to change special character to url encoded character

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));

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.