Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding my object inside JSON by its ID

[
    {"ID":"5","Name":"Jay"},
    {"ID":"30","Name":"Sharon"},
    {"ID":"32","Name":"Paul"}
]

So I have this kind of JSON.

I need to easily supply the value for a required key. For example:

  • 30 would yield => "Sharon"
  • 5 would yield => "Jay"

etc. What is the right way to do this?

like image 710
Ted Avatar asked Dec 12 '25 22:12

Ted


2 Answers

Iterate the array and check if the ID matches

function getById(id) {
    var O = null;
    for (var i=0; i<arr.length; i++) {
        if ( arr[i].ID == id ) return O = arr[i];
    }
    return O;
}

getById('30'); // returns {"ID":"30","Name":"Sharon"}

FIDDLE

or in newer browsers:

function getById(arr, id) {
   return arr.filter(function(o) { return o.ID == id });
}

FIDDLE

like image 149
adeneo Avatar answered Dec 15 '25 11:12

adeneo


Try a linear search:

var searchId = "30";
for(var i = 0; i < json.length; i++)
{
    if(json[i].ID == searchId)
    {
        // Found it.
        //

        break;
    }
}
like image 33
bugwheels94 Avatar answered Dec 15 '25 10:12

bugwheels94



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!