0

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;  
            }); 
        }
    });
}); 
irwan dwiyanto
  • 690
  • 1
  • 9
  • 28
  • 1
    *"and whether the script I got it right?"* - Well, what happened when you ran it? – nnnnnn Feb 22 '17 at 05:42
  • yes I expected how to look for `id` = 2 of data.json without using the query url – irwan dwiyanto Feb 22 '17 at 05:46
  • 1
    Possible duplicate of [Get JavaScript object from array of objects by value or property](http://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-or-property) – Rajesh Feb 22 '17 at 05:54

2 Answers2

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.

vinoth h
  • 511
  • 3
  • 11
0

You can use filter function to filter the data based on id

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

        var res = data.device.filter(function (obj) {
            return obj.id == 2;
        });

 if(res.length){
  console.log(res[0].id);
  console.log(res[0].name);
}
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40