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 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; | |
} |
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
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
I'm know this isn't the most performant thing, but it is a one-liner: