0

I'm trying to loop through an object and find a specific match. When I find a match, I want to pull the other key value pairs in the object. So if I have an object in this form:

[{"ID":"3","NAME":"John","Age":"15"},{"ID":"4","NAME":"Mike","Age":"10"},{"ID":"5","NAME":"Tim","Age":"18"},{"ID":"6","NAME":"Ken","Age":"20"}]

and I have a search/match value

var MatchValue = 4;

How can I iterate through my object to find the "ID" that equals 4 and display the "NAME" and "AGE" from the object? Any help on this would be greatly appreciated. Thanks in advance. #JsonNoob.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
user1898629
  • 329
  • 1
  • 4
  • 22

1 Answers1

0

What you are looking to do is filter your array. You can do this with JavaScript's filter function. This code will get you the elements where the ID is equal to 4.

You can then access this object's properties with either dot or bracket notation.

var myObject = array.filter(function(element) {
    return element.ID === '4';
}

console.log(myObject.name);     // Prints name to console
console.log(myObject.age);      // Prints age to console

If you have a browser from the stone ages, you can do this

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if (typeof fun != "function")
    throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in this) {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
        res.push(val);
      }
    }
    return res;
  };
}

I got this from another Stack Overflow answer, but I can explain it.

This checks if your browser has the Array.prototype.filter function. Some older versions of IE don't have it, so you can then define the function manually.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87