cargide cargide - 4 months ago 10
jQuery Question

Search the index of an ajax request element in javascript

I have an ajax response with data extracted from a sql query. It has this structure:

Response
id:"id"
titulo:"title"
url:"url"


What I am trying to do is to find the position within the ajax response where a given unique id is.

$.ajax({
url: 'select.php',
type: 'get',
data: {
"id": id
},
dataType: "json",
beforeSend: function() {},
success: function(response) {
console.log(response);
console.log(response.indexOf(27188964));
}
});


The second log prints
-1
, knowing that the number should be at the first position.

EDIT:
I need the position in order to start moving through the array by increasing 'index'
response[index].url

Answer

If your response is an array of objects you can use Array.prototype.filter():

$.ajax({
    url: 'select.php',
    type: 'get',
    data: {
        "id": id
    },
    dataType: "json",
    beforeSend: function() {},
    success: function(response) {
        var resultIndex;
        var result = response.filter(function(obj, index) {
            if (obj.id === '27188964') {
                resultIndex = index;
                return true;
            }
            return false;
        });

        console.log('resultIndex:', resultIndex);
        console.log('result:', result);
    }
});