Search a JavaScript object

Solution 1:

You might like using jLinq (personal project)

http://hugoware.net:4000/Projects/jLinq

Works like LINQ but for JSON and it allows you to extend it and modify it however you want to. There is already a bunch of prebuilt methods to check values and ranges.

Solution 2:

Seeing as though the only helpful answers have been referencing third party libraries - here's your native javascript solution. For anyone that only wants a few lines of code rather than a stack:

The function:

Array.prototype.findValue = function(name, value){
   var array = map(this, function(v,i){
        var haystack = v[name];
        var needle = new RegExp(value);
        // check for string in haystack
        // return the matched item if true, or null otherwise
      return needle.test(haystack) ? v : null;
   });
  return array;
}

A native .map() function:

map = function(array, mapFunction) {
      var newArray = new Array(array.length);
      for(var i = 0; i < array.length; i++) {
        newArray[i] = mapFunction(array[i]);
      }
      return newArray;
}

Your object:

(skimmed from your posted abject):

myObject = {
        name : "soccer",
        elems : [
            {name : "FC Barcelona"},
            {name : "Liverpool FC"}
        ]
    },
    {
        name : "basketball",
        elems : [
            {name : "Dallas Mavericks"}
        ]
    }

For usage:

(This will search your myObject.elems array for a 'name' matching 'FC')

var matched = myObject.elems.findValue('name', 'FC');
console.log(matched);

The result - check your console:

[Object, Object, findValue: function]
0: Object
name: "FC Barcelona"
__proto__: Object
1: Object
name: "Liverpool FC"
__proto__: Object
length: 2
__proto__: Array[0]