Created
November 20, 2012 03:48
-
-
Save mxriverlynn/4115824 to your computer and use it in GitHub Desktop.
Find key by value, with underscore.js
This file contains hidden or 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, value){ | |
var key; | |
_.each(_.keys(obj), function(k){ | |
var v = obj[k]; | |
if (v === value){ | |
key = k; | |
} | |
}); | |
return key; | |
} |
what about using _.find
to keep the number of loops down and returning after the first match?
function findKey(obj, value){
var key;
_.find(obj, function(v, k) {
if (v === 'bar') {
key = k;
return true;
} else {
return false;
}
});
return key;
}
sorry, v === value
Slight simplification. If passed an object, the arguments in _.each
's iterator are (value, key)
:
function findKey(obj, value) {
var key;
_.each(obj, function (v, k) {
if (v === value) {
key = k;
}
});
return key;
}
I'm know this isn't the most performant thing, but it is a one-liner:
_.invert(obj)[value]
Awesome one liner! super useful for small objects and avoiding self-defined-function-cruft :) (even though those are good options as well!)
π the one-liner for sheer simplicity
that works if all values are unique but none like that:
{a:2,b:2,c:2}.
When you invoke that invert function for the json you'll get new object with one key
π @digitalBush
π @digitalBush
ready to drop in underscore extension (mixin)
(function() {
"use strict";
// define global mixins within underscore.js
_.mixin({
findFirstKeyWhere:findFirstKeyWhere,
findKeyWhere:findKeyWhere
});
/**
* @function findFirstKeyWhere
* @desc Searches an object for the first key whos value matches the
* provided value otherwise returns undefined
* @param {Object} obj The object to search
* @param {*} value The value to compare
* @returns {String} The key of the matched value comparison
* @default Undefined
* @memberof _.mixin
*/
function findFirstKeyWhere(obj, value){
var key;
_.find(obj, function(v, k) {
if (v === value) {
key = k;
return true;
}
});
return key;
}
/**
* @function findKeyWhere
* @desc Searches an object for keys whos value matches the provided value
* otherwise returns an empty array
* @param {Object} obj The object to search
* @param {*} value The value to compare
* @returns {Array} An array of keys of the matched value comparison
* @default [] An empty Array
* @memberof _.mixin
*/
function findKeyWhere(obj, value){
var key = [];
_.find(obj, function(v, k) {
if (v === value) {
key.push(k);
}
});
return key;
}
})()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably throw a return false inside the if so it will short circuit that loop. I think that's a thing in underscore.