Get an Object's Key by Value in TypeScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Get an Object's Key by Value in TypeScript #

To get an object's key by value in TypeScript:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Type the array to be an array of the object's keys.
  3. Use the find() method to get the key by its value.
index.ts
const obj = { name: 'Tom', department: 'accounting', country: 'Chile', }; // ✅ Using Object.keys() const result1 = (Object.keys(obj) as (keyof typeof obj)[]).find((key) => { return obj[key] === 'accounting'; }); console.log(result1); // 👉️ "department" // ✅ Using Object.entries() let result2 = ''; Object.entries(obj).find(([key, value]) => { if (value === 'accounting') { result2 = key; return true; } return false; }); console.log(result2); // 👉️ "department"

Both of the examples in the code snippet get an object's key by value.

We used the Object.keys method in the first example. The method returns an array of the object's keys.

index.ts
const obj = { name: 'Tom', department: 'accounting', country: 'Chile', }; // 👇️ const r: string[] const r = Object.keys(obj); console.log(r); // 👉️ ['name', 'department', 'country']
However, note that TypeScript types the return value of the Object.keys() method as string[].

All of the object's keys are strings, but not all strings are keys in the object, so we wouldn't be able to access a value by key directly.

index.ts
const obj = { name: 'Tom', department: 'accounting', country: 'Chile', }; // 👇️ const r: string[] const r = Object.keys(obj).find((key) => { // ⛔️ Error: No index signature with a parameter of // type 'string' was found on type // '{ name: string; department: string; country: string; }'. return obj[key] === 'accounting'; });

TypeScript is telling us that we can't index the object with any string key, it has to be name, department or country.

This is why we used a type assertion to type the return value of the Object.keys() method.

index.ts
const obj = { name: 'Tom', department: 'accounting', country: 'Chile', }; // now the `key` parameter is typed as // 👇️ (parameter) key: "name" | "department" | "country" const result1 = (Object.keys(obj) as (keyof typeof obj)[]).find((key) => { return obj[key] === 'accounting'; }); console.log(result1); // 👉️ "department"

Now the key parameter in the find method is a union type of the objects keys, so everything works as expected.

The function we passed to the Array.find method gets called with each element in the array of keys until it returns a truthy value or iterates over the entire array.

If the condition is met, the find() method returns the corresponding array element and short-circuits.

If the condition is never satisfied, find() returns undefined.

You can also use the Object.entries() method to get an object's key by its value.

index.ts
const obj = { name: 'Tom', department: 'accounting', country: 'Chile', }; let result2 = ''; Object.entries(obj).find(([key, value]) => { if (value === 'accounting') { result2 = key; return true; } return false; }); console.log(result2); // 👉️ "department"

Notice that we don't have to use type assertions when using this approach.

The Object.entries method returns an array of key-value pairs.

index.ts
const obj = { name: 'Tom', department: 'accounting', country: 'Chile', }; // 👇️ const r: [string, string][] const r = Object.entries(obj); // 👇️ [['name', 'Tom'], ['department', 'accounting'], ['country', 'Chile']] console.log(r);
This is useful, because we don't have to use a type assertion as we get an array of 2 elements - the key and value.

The find() method returns the array element for which the condition is met or an undefined value and we only want the key, so it's simpler to:

  1. Initialize a variable outside of the method
  2. Set its value once the condition is met
  3. Short-circuit
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.