Last active
August 29, 2015 13:56
-
-
Save larchanka/9953257fe957f2470089 to your computer and use it in GitHub Desktop.
Function allows to find entity in array/object by key and value. @param `keyObj` – key and value, i.e. {id:10}.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Object.prototype.findEntity = function(keyObj) { | |
var arr = this, p, key, val, ret; | |
for (p in keyObj) { | |
if (keyObj.hasOwnProperty(p)) { | |
key = p; | |
val = keyObj[p]; | |
} | |
} | |
for (p in arr) { | |
if (p == key) { | |
if (arr[p] == val) { | |
return arr; | |
} | |
} else if (arr[p] instanceof Object) { | |
if (arr.hasOwnProperty(p)) { | |
ret = findEntity(arr[p], keyObj); | |
if (ret) { | |
return ret; | |
} | |
} | |
} | |
} | |
return false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment