Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Generate variables from JSON to use in string template (Javascript)

I have some JSON that looks a little like this:

component.json

[
  { "template": "<div class="${layout} ${border}"></div>" },
  {
    "layout": "grid",
    "border": "primary"
  }
]

I'm using this JSON to generate some HTML via JS, and I can't work out how to turn "layout" and "border" into variables that I can then add into my template string.

For context I can't just hard code the variables, in my JSON I can't predict how many variables there will be or what they are.

I'm trying something like this:

const template = componentJSON[0].template
const classes = componentJSON[1]

for (const [key, value] of Object.entries(classes)) {
    eval('var ' + `${key}` + ' = ' + '"' + `${value}` + '"')
}

let html = eval('`' + template + '`')

I am aware of the EVIL that is eval, so I'm happy to hear other solutions, but also happy to hear options with eval as this will never be exposed to attacks.

I'm not sure why my for loop that should create the variables using eval isn't working? Maybe eval is built specifically not to create variables? Could I use new Function() instead somehow?

For the reference the result I'm hoping for should be:

<div class="grid primary"></div>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There's no need to use eval() for this. Use the replace() method with a regexp that matches ${...} and replaces with the corresponding object property.

let componentJSON = [
  { "template": "<div class='${layout} ${border}'></div>" },
  {
    "layout": "grid",
    "border": "primary"
  }
];

const template = componentJSON[0].template
const classes = componentJSON[1]

let html = template.replace(/\$\{(.*?)\}/g, (match, key) => classes[key]);

console.log(html);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda