Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading