How do you find an object's key name by its corresponding value in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you find an object's key name by its corresponding value in JavaScript?

message-square
0

To find an object’s key name by its corresponding value in JavaScript, use Object.entries(obj).find(([, value]) => value === target) (or Object.keys(obj).find((key) => obj[key] === target)), which inspects own enumerable string properties without walking the prototype chain and returns the first matching key (or undefined if no match exists). Because object values can be duplicated or non-unique, also consider collecting all matching keys with .filter() or using a reverse Map when performing frequent reverse lookups.


1. Finding the First Key by Value with Object.entries() and .find()

Use Object.entries(obj).find(([, value]) => Object.is(value, targetValue)) (or ===) to find the first own property key whose value matches targetValue:

// Find the first own property key matching a target value (handles NaN via Object.is)
function findKeyByValue(obj, targetValue) {
  if (obj === null || typeof obj !== "object") {
    throw new TypeError("Expected obj to be a non-null object.");
  }

  const match = Object.entries(obj).find(([, value]) => Object.is(value, targetValue));
  return match ? match[0] : undefined;
}

// Example usage:
const statusCodes = {
  ok: 200,
  created: 201,
  badRequest: 400,
  notFound: 404
};

console.log(findKeyByValue(statusCodes, 201)); // "created"
console.log(findKeyByValue(statusCodes, 500)); // undefined
  • Avoids prototype keys (for...in pitfall): Object.entries() only checks own enumerable properties, so "toString" or "valueOf" will not be matched accidentally.
  • Handles NaN cleanly: Using Object.is() matches NaN reliably whereas === treats NaN === NaN as false.

2. Finding All Keys That Share the Same Value

Unlike keys, object values are not unique—multiple keys can hold the same value, so use Object.entries(obj).filter(...) when you need every matching key:

// Collect all own property keys matching a given value
function findAllKeysByValue(obj, targetValue) {
  if (obj === null || typeof obj !== "object") {
    throw new TypeError("Expected obj to be a non-null object.");
  }

  return Object.entries(obj)
    .filter(([, value]) => Object.is(value, targetValue))
    .map(([key]) => key);
}

// Example usage:
const permissions = {
  readDocs: "editor",
  editPosts: "editor",
  viewLogs: "viewer",
  deleteUsers: "admin"
};

console.log(findAllKeysByValue(permissions, "editor")); // ["readDocs", "editPosts"]
console.log(findAllKeysByValue(permissions, "guest"));  // []
  • Returns an array (possibly empty): Cleanly distinguishes zero matches ([]) from one (["viewLogs"]) or many (["readDocs", "editPosts"]).
  • Non-mutating: Leaves the source object untouched.

3. Reverse Lookup Maps and Reference Gotchas

A linear scan with Object.entries() runs in O(n) time per lookup and compares objects/arrays by reference ({ a: 1 } !== { a: 1 }); for repeated reverse lookups or bi-directional mappings, build a reverse Map once:

// Build a reverse Map for fast O(1) value-to-key lookups when values are unique
function buildReverseMap(obj) {
  if (obj === null || typeof obj !== "object") {
    throw new TypeError("Expected obj to be a non-null object.");
  }

  const reverse = new Map();
  for (const [key, value] of Object.entries(obj)) {
    if (!reverse.has(value)) {
      reverse.set(value, key);
    }
  }
  return reverse;
}

// Example usage:
const localeToCode = { en: 1, ur: 2, ar: 3 };
const codeToLocale = buildReverseMap(localeToCode);
console.log(codeToLocale.get(2)); // "ur"
  • Reference equality for objects/arrays: If a property value is an object or array, value === candidate only matches the exact same reference in memory.
  • Collision handling: If two keys share a value, a reverse Map keeps the first key unless explicitly overwritten or stored as an array of keys.