Created
February 22, 2013 09:53
-
-
Save bungoume/5012201 to your computer and use it in GitHub Desktop.
Search a JavaScript Object
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
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