javascript - JS jQuery each loop filter append list -


i making ajax call grabs data looks this:

{     "cars":[{         "id":"654",         "type": "ford",         "active": "1"     },{         "id":"650",         "type": "fiat",         "active": "0"     }] }  

i use data populate selectbox code:

$.ajax({     url: 'myurlhere',     method: 'get',     async: false,     success: function(result) {          $.each(result, function(result, value) {             $('#myselect').append($('<option>').text(value.id).attr('value', value.id));         });      } }); 

my problem want populate select data have active = "1" (for data)

so i've done this:

$.ajax({     url: 'myurlhere',     method: 'get',     async: false,     success: function(result) {          if (value.active = 1) {             $.each(result, function(result, value) {                 $('#myselect').append($('<option>').text(value.id).attr('value', value.id));             });         }      } }); 

but not filtering , still returning all.

how can fix this?

firstly need remove async: false it's bad practice use it.

secondly, can use filter() on result.cars array find active '1':

var data = result.cars.filter(function(obj) {     return obj.active == '1'; })  $.each(data, function(result, value) {     $('#myselect').append($('<option>', {         text: value.id,         value: value.id     })); }); 

alternatively in $.each loop itself, note need loop through result.cars, not result:

$.each(result.cars, function(i, value) {     if (value.active == '1') {         $('#myselect').append($('<option>', {             text: value.id,             value: value.id         }));     } }); 

it depend on how many active elements in array of above methods quicker, although there won't of difference in real terms. ideally amend response return active objects, assume third party api , therefore out of control.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -