gafasmill gafasmill - 4 months ago 30
jQuery Question

JS jQuery each loop filter append list

I am making an ajax call with grabs data which looks like this:

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


I then use the data to populate a selectbox with this 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 is that I only want to populate the select with data which have active = "1" (for the 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 this is not filtering it and still returning all.

How can I fix this?

Answer

Firstly you need to remove async: false as it's very bad practice to use it.

Secondly, you can use filter() on the result.cars array to find only this where active is '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 you could do it in the $.each loop itself, but note that you need to 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 would depend on how many active elements are in the array as to which of the above methods would be quicker, although there probably won't be much of a difference in real terms. Ideally you could amend the response to only return active objects, but I assume this is a third party API and therefore out of your control.