Search code examples
javascriptjsonobjectlodash

I want to return a key using Lodash when it contains a particular value


I have an object like this:

const obj = {
  'MONEY-OUT': {
    USD: ['a', 'b', 'c'],
    EUR: ['d', 'e', 'f'],
  },
  'MONEY-IN': {
    USD: ['g', 'h', 'i'],
    EUR: ['j', 'k', 'l'],
  },
};

and I want to create a function that returns either the key MONEY-OUT / MONEY-IN if that key contains a character in its array using Lodash. I have 2 variables in this function: currency, search_string

For example, my variable values for this function are 'EUR' and 'k' so I need my function to return the key MONEY-IN


Solution

  • There's zero reason to use Lodash or any other utility library for this.

    You can use Array.prototype.find() to find the first object entry (key / value) pair matching your criteria, then return the key for that entry

    const obj = {
      'MONEY-OUT': {
        USD: ['a', 'b', 'c'],
        EUR: ['d', 'e', 'f'],
      },
      'MONEY-IN': {
        USD: ['g', 'h', 'i'],
        EUR: ['j', 'k', 'l'],
      },
    };
    
    const findKey = (currency, search_string) =>
      Object.entries(obj).find(([, v]) =>
        v[currency]?.includes(search_string),
      )?.[0];
    
    console.log('EUR[k]', findKey('EUR', 'k'));
    console.log('USD[b]', findKey('USD', 'b'));
    console.log('GBP[z]', findKey('GPB', 'z'));