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-
  • 209,133
  • 54
  • 439
  • 449
Ted
  • 3,643
  • 11
  • 52
  • 97

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
  • 303,455
  • 27
  • 380
  • 377
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
  • 38,275
  • 19
  • 91
  • 162
bugwheels94
  • 28,872
  • 3
  • 36
  • 59
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"];
    }
}
Neuticle
  • 614
  • 3
  • 9
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