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
Get key from value in JavaScript
In JavaScript, finding a key from its corresponding value in an object requires iterating through the object's key-value pairs. Unlike accessing values by keys (which is direct), reverse lookup needs a search operation.
Understanding the Problem
Given a JavaScript object and a value, we need to find the key that maps to that value. For example:
{
key1: 'value1',
key2: 'value2',
key3: 'value3'
}
If we search for 'value2', we should get 'key2' as the result.
Using Object.entries() and find()
The most efficient approach uses Object.entries() to convert the object into key-value pairs, then find() to locate the matching value:
function getKeyByValue(obj, value) {
const entry = Object.entries(obj).find(([key, val]) => val === value);
return entry ? entry[0] : null;
}
const appObj = {
Application1: 'Learning',
Application2: 'Ecommerce',
Application3: 'Software',
Application4: 'Business'
};
console.log(getKeyByValue(appObj, 'Ecommerce')); // Application2
console.log(getKeyByValue(appObj, 'Business')); // Application4
console.log(getKeyByValue(appObj, 'NotFound')); // null
Application2 Application4 null
Using for...in Loop
A traditional approach using a for...in loop for better readability:
function getKeyByValueLoop(obj, value) {
for (let key in obj) {
if (obj[key] === value) {
return key;
}
}
return null;
}
const colors = {
red: '#FF0000',
green: '#00FF00',
blue: '#0000FF'
};
console.log(getKeyByValueLoop(colors, '#00FF00')); // green
console.log(getKeyByValueLoop(colors, '#FFFFFF')); // null
green null
Finding All Keys for a Value
If multiple keys have the same value, you can find all matching keys:
function getAllKeysByValue(obj, value) {
return Object.entries(obj)
.filter(([key, val]) => val === value)
.map(([key]) => key);
}
const roles = {
admin: 'full_access',
editor: 'edit_access',
viewer: 'read_access',
guest: 'read_access'
};
console.log(getAllKeysByValue(roles, 'read_access'));
console.log(getAllKeysByValue(roles, 'full_access'));
[ 'viewer', 'guest' ] [ 'admin' ]
Comparison of Methods
| Method | Performance | Readability | Multiple Results |
|---|---|---|---|
Object.entries() + find() |
Good | High | No |
for...in loop |
Best | Medium | No |
Object.entries() + filter() |
Good | High | Yes |
Time Complexity
All methods have O(n) time complexity in the worst case, where n is the number of properties in the object. Space complexity is O(1) for single result methods and O(k) for methods returning multiple keys, where k is the number of matching keys.
Conclusion
Use Object.entries() with find() for clean, readable code when finding a single key. For performance-critical applications, the for...in loop provides slightly better performance with early termination.
