Skip to content

Instantly share code, notes, and snippets.

@larchanka
Last active August 29, 2015 13:56
Show Gist options
  • Save larchanka/9953257fe957f2470089 to your computer and use it in GitHub Desktop.
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}.
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