Get the value of the data based on the `id` with ajax json

I have data with json format, and I tried to show her with ajax and successfully. but how to find one id in json using ajax? and whether the script I got it right? example I want to find id 2.

My json

{ "device": [
    {
        "id": 1,
        "name": "Android"
    },
    {
        "id": 2,
        "name": "Apel"
    },
    {
        "id": 3,
        "name": "Windows"
    }
] }

My ajax

$(document).ready(function() {
    var id_pm = 2 ;
    var dataString = "id="+id_pm;   
    $.ajax({
        type: "GET",
        url: "data.json",
        data: dataString,
        cache: false,
        timeout: 3000,
        error: function(){
            alert('Error');
        },              
        success: function(result){
            var result=$.parseJSON(result);
            $.each(result, function(i, element){        
                var id=element.id;
                var name=element.name;  
            }); 
        }
    });
}); 

Answers 1

  • Id's are meant to be unique.If your JSON does not contain sequential id's then you will have to sequentially scan all the objects like this :

    //put this inside your success callback.
    var mysearchId = 2;
    //res is now array of all your devices.
    var res = (JSON.parse(result)).device;
    for(var i = 0;i < res.length;i ++) {
        if(res[i].id == mysearchId) {
          console.log(res[i]);
          return;
        }
    }
    console.log('not found!');
    

    This finds the desired item in O(N) time.

    In case your id's are sequential you can find a particular element in O(1) time.To achieve this,the devices array must be sorted. For example if you want to find element with id 10 you can access it by res[(10-1)]; //==>res[9]; provided the first item has id=1.


Related Articles