2
[
    {"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?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Ted
  • 3,805
  • 14
  • 56
  • 98

5 Answers5

5

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

adeneo
  • 312,895
  • 29
  • 395
  • 388
3

Try a linear search:

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

        break;
    }
}
Marty
  • 39,033
  • 19
  • 93
  • 162
bugwheels94
  • 30,681
  • 3
  • 39
  • 60
2

If the IDs will be unique, and if you're going to need to do this frequently, then you may want to convert your collection to key/value pairs where the ID is the key.

var byId = data.reduce(function(res, obj) {
    res[obj.ID] = obj;
    return res
}, {});

Now you can simply use the ID to look up the object.

var target = byId["30"];
1

You could probably just write something to loop through it.

var data = [ {"ID":"5","Name":"Jay"},{"ID":"30","Name":"Sharon"}, {"ID":"32","Name":"Paul"} ];
for(var i in data){
    if(data[i]["ID"] == 30){
      return data[i]["Name"];
    }
}
Adam
  • 772
  • 3
  • 10
0

undersocre.js can find a object in collection by one line code

Reference: http://underscorejs.org/#find

Code:

var people = [
    {"ID":"5","Name":"Jay"},
    {"ID":"30","Name":"Sharon"},
    {"ID":"32","Name":"Paul"}
];

_.find(people, function(person) { return person.ID === '5'; });

FIDDLE

Ikhoon Eom
  • 183
  • 2
  • 7