Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Fetching JavaScript keys by their values - JavaScript
In JavaScript, you can find an object key by its value using several approaches. This is useful when you need to perform reverse lookups in objects where both keys and values are unique.
Consider this object where we want to find keys by their corresponding values:
const products = {
"Pineapple": 38,
"Apple": 110,
"Pear": 109
};
console.log(products);
{ Pineapple: 38, Apple: 110, Pear: 109 }
Using Object.keys() with find()
The most straightforward approach uses Object.keys() with find() to locate the key:
const products = {
"Pineapple": 38,
"Apple": 110,
"Pear": 109
};
const findKeyByValue = (obj, value) => {
return Object.keys(obj).find(key => obj[key] === value);
};
console.log(findKeyByValue(products, 110)); // "Apple"
console.log(findKeyByValue(products, 38)); // "Pineapple"
console.log(findKeyByValue(products, 999)); // undefined
Apple Pineapple undefined
Using Reverse Mapping
For frequent lookups, create a reverse map once and reuse it:
const products = {
"Pineapple": 38,
"Apple": 110,
"Pear": 109
};
const createReverseMap = (obj) => {
const reverseMap = {};
Object.keys(obj).forEach(key => {
reverseMap[obj[key]] = key;
});
return reverseMap;
};
const reverseProducts = createReverseMap(products);
console.log(reverseProducts);
// Now lookup is O(1)
console.log(reverseProducts[110]); // "Apple"
console.log(reverseProducts[38]); // "Pineapple"
{ '38': 'Pineapple', '109': 'Pear', '110': 'Apple' }
Apple
Pineapple
Using Object.entries()
Another approach uses Object.entries() to work with key-value pairs directly:
const products = {
"Pineapple": 38,
"Apple": 110,
"Pear": 109
};
const findKeyByValue = (obj, value) => {
const entry = Object.entries(obj).find(([key, val]) => val === value);
return entry ? entry[0] : undefined;
};
console.log(findKeyByValue(products, 110)); // "Apple"
console.log(findKeyByValue(products, 109)); // "Pear"
Apple Pear
Comparison
| Method | Performance | Best For |
|---|---|---|
Object.keys().find() |
O(n) per lookup | One-time lookups |
| Reverse Mapping | O(1) per lookup | Frequent lookups |
Object.entries().find() |
O(n) per lookup | Working with pairs |
Conclusion
Use Object.keys().find() for simple cases and reverse mapping for performance-critical applications with frequent lookups. Both approaches handle missing values gracefully by returning undefined.
Advertisements
