d
Amit DhamuSoftware Engineer
 

Get object key based on value

1 minute read 00000 views

To find the key of the object below based on a value in the arrays, we can do:

const obj = {
  fruit: ['banana', 'apple', 'orange'],
  veg: ['cabbage', 'carrot', 'pepper'],
  drink: ['milk'],
}

const getKey = toFind => Object.keys(obj).find(key => obj[key].includes(toFind))

getKey('apple') // returns fruit
getKey('carrot') // returns veg

Similarly, if our object didn't have arrays but single values, we could do

const obj = {
  starter: 'garlic bread',
  main: 'cheese pizza',
  drink: 'coca-cola',
}

const getKey = toFind => Object.keys(obj).find(key => obj[key] === toFind)

getKey('garlic bread') // returns starter
getKey('cheese pizza') // returns main