Search code examples
javascriptlodash

Get object key based on value inside that object


I am trying to get the key that is associated with a certain value. If I use this:

function findKpiAttrName (obj, value) {
  _.each(obj, function (v, k) {
    if (v.hasOwnProperty('name') && v.name === value) { return k }
  });
}

var attrKey = findKpiAttrName(obj, 'KPI Name');

If I console.log(attrKey) it returns undefined but I know it is finding something because if I console.log(k) inside the above method it prints it just fine. Is there something wrong with scope that I am missing? I am using ES5 by the way.

Any help with be great! Thanks!


Solution

  • Maybe something like this:

    function findKpiAttrName (obj, value) {
      let d = null;
      _.each(obj, function (v, k) {
        if (v.hasOwnProperty('name') && v.name === value) { d = k; return false; }
      });
      return d;
    }
    

    Or maybe this is even better:

    function findKpiAttrName(obj, value) {
      for (let [k, v] of Object.entries(obj)) {
        if ( v.hasOwnProperty('name') && v.name === value) {
          return k;
        }
      }
    }