0

Let there is an object which has values as arrays. For example,

    const obj = {
      'abc': ['xyz','tuv'],
      'def': ['qrs']
    }

How can we get the key of 'tuv' from the object?

This is different from this question, where the value was not an array. How to get a key in a JavaScript object by its value?

Reza
  • 2,896
  • 4
  • 26
  • 37
  • Are you looking for a result of 'abc' given the value 'tuv'? – Grax32 Jan 17 '20 at 11:47
  • Does this answer your question? [How to get a key in a JavaScript object by its value?](https://stackoverflow.com/questions/9907419/how-to-get-a-key-in-a-javascript-object-by-its-value) – VLAZ Jan 17 '20 at 11:51
  • 1
    Not an exact dupe, since it's doing an exact match of the value to get the key but the only change needed is to add array lookup instead of exact matching. And array lookup is a trivial task that is a solved problem. – VLAZ Jan 17 '20 at 11:52

2 Answers2

3

You could get the keys and filter by checking the values.

const
    getKeys = (object, value) => Object.keys(object).filter(k => object[k].includes(value)),
    obj = { abc: ['xyz','tuv'], def: ['qrs'] };
    
console.log(getKeys(obj, 'tuv'));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

I am assuming one value will not have multiple keys.

const getKeyByValue = (object, value) => Object.keys(object)
  .map(key => object[key].map(val => { if (val === value) { return key }}))
  .flat().filter(key => key)[0] || false

So, if we want to get the key of 'tuv', we can call this method like this,

getKeyByValue(obj, 'tuv')
Reza
  • 2,896
  • 4
  • 26
  • 37