skip to Main Content

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

2

Answers


  1. 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'));
    Login or Signup to reply.
  2. Since the answer you are searching for a lodash based solution and above

    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

    @Phil provided answer is based upon Array.prototype.find(), Here’s how you can achieve what you are looking for using the library lodash:

    Refer the below code for reference:

    const obj = {
          'MONEY-OUT': {
            USD: ['a', 'b', 'c'],
            EUR: ['d', 'e', 'f'],
          },
          'MONEY-IN': {
            USD: ['g', 'h', 'i'],
            EUR: ['j', 'k', 'l'],
          },
        };
    
        function findKeyByValue(obj, currency, search_string) {
          return _.findKey(obj, (value) => {
            return _.get(value, currency, []).includes(search_string);
          });
        }
    
        function findKeyAndCurrency(obj, currency, search_string) {
          const topKey = findKeyByValue(obj, currency, search_string);
          return topKey ? { topKey, currency } : null;
        }
    
        console.log(JSON.stringify(findKeyAndCurrency(obj, 'EUR', 'k')));
        console.log(JSON.stringify(findKeyAndCurrency(obj, 'USD', 'g')));
        console.log(JSON.stringify(findKeyAndCurrency(obj, 'USD', 'a')));
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js">   
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search