vendredi 7 avril 2017

Basic loop for using (javascript) with condition

need your help for my problem. Let say I have an object and an array as my list on my javascript as below:

     var hotel={  "electronic":[
      {  "id":1,
      "tv":"LG"},
    {  "id":2,
      "tv":"Polytron"},
    {  "id":3,
      "tv":"Panasonic"},
    {  "id":4,
      "tv":"Sony"},
      ]
    }
    var mylist=[1,2,1,4,2,3,2,4];
    var mytran;
    var i=0;  
    
    while(i<mylist.length){
    if(mylist[i]===1){
    mytran=hotel.electronic[0].tv;
    }
    else if(mylist[i]===2){
    mytran=hotel.electronic[1].tv;
    }
    else if(mylist[i]===3){
    mytran=hotel.electronic[2].tv;
    }
    else if(mylist[i]===4){
    mytran=hotel.electronic[3].tv;
    }
    console.log(mytran);
    i++;
    }
    

The above code is working, but actually I get the object data from my db which is only have 4 object inside array 'electronic'. My concern is how if I have hundreds object on my electronic data array. It will be have hundreds of if else as well. Do you think we still can to optimize my code? Please your explaination.

Aucun commentaire:

Enregistrer un commentaire