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

238
Visualizações
How to get data value with in a loop

Hi I want to get alert "lkb_1" and "lkb_2" , but this code gives me "product_1_name" and "product_1_name" ;

eval and window functions I can get rid of them but I think they are not recommended to do that.. so is there any other solution rather than eval and window functions?

<script>
  product_1_name = "lkb_1";
  product_1_pcs = 3;
  product_2_name = "lkb_2";
  product_2_pcs = 5;
  profil_ismi = "";

  const profil_listesi = ["product_1", "product_2"];
  i = 0;
  while (i < profil_listesi.length) {
    profil_ismi = profil_listesi[i] + "_name";
    alert(profil_ismi);
    i = i + 1;
  }

</script>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

To avoid using eval you can do that.

The thing would work well if you wrap the product names in an array. then you can dynamically create the variable name and thus specifically retrieve the value in the array.

arr = []
arr['product_1_name'] = "lkb_1" ;
product_1_pcs       = 3 ;
    
arr['product_2_name'] = "lkb_2" ;
product_2_pcs       = 5 ;
                    
profil_ismi = "" ;
    
const profil_listesi = ["product_1","product_2"];
let i=0;
while (i<profil_listesi.length)
{
  let _name = profil_listesi[i] + '_name'
   profil_ismi     = arr[_name];
       
   alert (profil_ismi) ;
    
   i=i+1;
}

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use eval in this case. It is safe, because it is evident that it cannot be misused for code injection in this particular case.

Still, I think it would be better (more scalable, more future proof), to have an array of products, as follows:

var products = [
  { id: 'product_1', name: 'lkb_1', pcs: '3'},
  { id: 'product_2', name: 'lkb_2', pcs: '5'}
];

const profil_listesi = ["product_1", "product_2"];
i = 0;
while (i < profil_listesi.length) {
  profil_ismi = products.find(p => p.id === profil_listesi[i])
  alert(profil_ismi.name);
  i = i + 1;
}

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