Skip to content

Instantly share code, notes, and snippets.

@bungoume
Created February 22, 2013 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bungoume/5012201 to your computer and use it in GitHub Desktop.
Save bungoume/5012201 to your computer and use it in GitHub Desktop.
Search a JavaScript Object
function findKey(obj, searchValue){
for (var key in obj){
if (_.has(obj, key) && obj[key]==searchValue){
return key;
}
}
}
findKey({a:1,b:2,c:3},3);//-->'c'
function findKey2(obj, searchValue){
var ret=[];
for (var key in obj){
if (_.has(obj, key) && obj[key]==searchValue){
ret.push(key);
}
}
return ret;
}
findKey2({a:1,b:2,c:3},3);//-->['c']
function findKey3(obj, searchValue){
_.reduce(obj,function(memo, value, key){if(value==searchValue)memo.push(key); return memo},[])
}
findKey3({a:1,b:2,c:3},3);//-->['c']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment