How to get an object key on a nested object if you know one of its properties values?

Viewed 28

I have an object like this:

const CATEGORY_SLUGS = {
  CATEGORY_1: { ES: "slug1-in-spanish", UK: "slug1-in-english" },
  CATEGORY_2: { ES: "slug2-in-spanish", UK: "slug2-in-english" },
  CATEGORY_3: { ES: "slug3-in-spanish", UK: "slug3-in-english" },
}

And in other part of my code I have the slug value, and the country is also known.

From those two information, what is the best way to know the CATEGORY? I mean, how to find out which category that slug refers to?

I can do it using a let variable and a for loop of some kind to check one by one and see what matches. But it's not looking good and I feel that there is a much cleaner solution out there.

1 Answers

You can use Object.entries and Array.find:

const CATEGORY_SLUGS = {
  CATEGORY_1: { ES: "slug1-in-spanish", UK: "slug1-in-english" },
  CATEGORY_2: { ES: "slug2-in-spanish", UK: "slug2-in-english" },
  CATEGORY_3: { ES: "slug3-in-spanish", UK: "slug3-in-english" },
}

const findKey = (country, slug) => {
  const entries = Object.entries(CATEGORY_SLUGS)
  const pair = entries.find(([_, category]) => category[country] === slug)
  return pair ? pair[0] : null
}
  

// Test case
console.log(findKey('ES', 'slug1-in-spanish'))
console.log(findKey('UK', 'slug2-in-english'))

// Error case
console.log(findKey('ES', 'slug3-in-english'))

Just a side note - just because it looks cleaner doesn't mean it's better. Readability is much preferred over short code.

Related