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?

3
  • Are you looking for a result of 'abc' given the value 'tuv'? Commented Jan 17, 2020 at 11:47
  • Does this answer your question? How to get a key in a JavaScript object by its value? Commented Jan 17, 2020 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. Commented Jan 17, 2020 at 11:52

2 Answers 2

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'));

Sign up to request clarification or add additional context in comments.

Comments

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')

2 Comments

object[key].map(val => { if (val === value) { return key }}) should probably be filter?
Yeah, that would be another way of doing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.