en algún lugar de los datos de la API obtengo una cadena normal como, "Hola ${persona[0].nombre}" ahora esta cadena la estoy convirtiendo en una cadena de plantilla y reemplazando sus variables de una matriz de objetos.
Aquí hay un fragmento que estoy tratando de ejecutar, y no obtengo el resultado esperado
const getObjPath = (path, obj, fallback = `$\{${path}}`) => { if (path && obj) return path.split('.').reduce((res, key) => res[key] || fallback, obj); return path; }; const interpolate = (template, variables, fallback) => { const regex = /\${[^{]+}/g; if (template && variables) { return template.replace(regex, (match) => { let path = match.slice(2, -1).trim(); path = path.split('|').map((item) => item.trim()); const fieldValue = getObjPath(path[0], variables, fallback); if (fieldValue) return fieldValue; return path[1] || fallback; }); } return template; }; const data = { person: [{ name: 'John', age: 18 }] }; const a = interpolate('Hi ${person?.[0]?.name | text} (${person?.[0]?.age | text})', data); console.log(a); salida: "Hi ${person?.[0]?.name} (${person?.[0]?.age})"
salida esperada: "Hi John 18"
¿Alguien puede decirme qué estoy haciendo mal aquí?
El problema es que la división de su ruta en getObjPath no trata con corchetes en la ruta.
Así que reemplaza esto
path.split('.')con:
path.match(/[^.[\]]+/g) const getObjPath = (path, obj, fallback = `$\{${path}}`) => { if (path && obj) return path.match(/[^.[\]]+/g).reduce((res, key) => res[key] || fallback, obj); return path; }; const interpolate = (template, variables, fallback) => { const regex = /\${[^{]+}/g; if (template && variables) { return template.replace(regex, (match) => { let path = match.slice(2, -1).trim(); path = path.split('|').map((item) => item.trim()); const fieldValue = getObjPath(path[0], variables, fallback); if (fieldValue) return fieldValue; return path[1] || fallback; }); } return template; }; const data = { person: [{ name: 'John', age: 18 }] }; const a = interpolate('Hi ${person[0].name | text} (${person[0].age | text})', data); console.log(a);