user6552641
user6552641

Reputation:

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?

Upvotes: 1

Views: 1317

Answers (3)

Sainath Batthala
Sainath Batthala

Reputation: 611

Let me know if it doesn't work.
Hope this helps.

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

Upvotes: 0

Glyde Burdick
Glyde Burdick

Reputation: 31

Your if statement is doing an assignment, not checking equality, for starters. Needs to be value.active === "1" Also, you want the if statement inside the .each method, not outside.

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 2

Related Questions