Jquery - Compare 2 arrays in each

Asked

Viewed 530 times

0

I have the following function:

function pre() {
        $.ajax({
            url: "arquivo1.php",
            method: 'POST',
            dataType: 'json',
            success: function (data) {
                $.ajax({
                    url: "arquivo2.php",
                    method: 'POST',
                    dataType: 'json',
                    success: function (data2) {

                    $.each(data.id, function(i, item) {

                        $( ".lado" ).prepend("<div id='" + data.id + "'><select class='select'></select></div>");

                        if (data.id == data2.id) {
                            $( ".select" ).append("<option'>" + data2.id + "</option>");
                        }
                    });

                }
            });
        }
    });

}

Are 2 ajax one inside the other that need to compare 2 different tables and generate the list of selects and the options of the selects, the if separates the options that are not of such select.

  • 1

    Your problem is just comparing if the two arrays are equal?

  • no, I need to compare and when I have equal item in arrays it lists, and are several equal items with the same id for example, type 3 items in "data1" equal in "data2"

2 answers

1


In that case you need 2 $.each.
Thus:

    // primeiro laço 
    $.each(data, function(key_data_first, item_first) {

        // segundo laço
        $.each(data, function(key_data_second, item_second) {

            // cria o select
            $( ".lado" ).prepend("<div id='" + item_first.id + "'><select id='select_" + item_first.id + "' class='select'></select></div>");

            //insere as opções no select
            if (item_first.id == item_second.id) {
                $("#select_"+item_first.id).append("<option>" + item_second.id + "</option>");
            }
        });
    });

0

If what’s inside the id of each data is an array, reason to use the $.each, can do so:

$.each(data.id, function(i, item) {
  $(".lado").prepend("<div id='" + data.id + "'><select class='select'></select></div>");
  if (item == data2.id[i]) {
    $(".select").append("<option'>" + data2.id + "</option>");
  }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.