Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created November 20, 2012 03:48
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mxriverlynn/4115824 to your computer and use it in GitHub Desktop.
Save mxriverlynn/4115824 to your computer and use it in GitHub Desktop.
Find key by value, with underscore.js
function findKey(obj, value){
var key;
_.each(_.keys(obj), function(k){
var v = obj[k];
if (v === value){
key = k;
}
});
return key;
}
@samandmoore
Copy link

Probably throw a return false inside the if so it will short circuit that loop. I think that's a thing in underscore.

@camacho
Copy link

camacho commented Nov 20, 2012

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;
}

@camacho
Copy link

camacho commented Nov 20, 2012

sorry, v === value

@jclem
Copy link

jclem commented Nov 20, 2012

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;
}

@digitalBush
Copy link

I'm know this isn't the most performant thing, but it is a one-liner:

_.invert(obj)[value]

@michahell
Copy link

Awesome one liner! super useful for small objects and avoiding self-defined-function-cruft :) (even though those are good options as well!)

@gdibble
Copy link

gdibble commented Feb 5, 2016

👍 the one-liner for sheer simplicity

@AndrewEastwood
Copy link

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

@stillwyw
Copy link

@Gerst20051
Copy link

@haxxxton
Copy link

haxxxton commented Sep 8, 2016

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