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
Reverse mapping an object in JavaScript
Reverse mapping an object in JavaScript involves swapping the keys and values of an object. This technique is useful when you need to look up keys based on their values.
Suppose we have an object like this:
const products = {
"Pineapple": 38,
"Apple": 110,
"Pear": 109
};
All the keys are unique in themselves and all the values are unique in themselves. We need to write a function that accepts a value and returns its corresponding key.
Method 1: Using Object.keys() with map()
This approach creates a reverse-mapped object by iterating through all keys and swapping them with their values:
const products = {
"Pineapple": 38,
"Apple": 110,
"Pear": 109
};
const findKey = (obj, val) => {
const res = {};
Object.keys(obj).map(key => {
res[obj[key]] = key;
});
// if the value is not present in the object, return false
return res[val] || false;
};
console.log(findKey(products, 110));
console.log(findKey(products, 38));
console.log(findKey(products, 999)); // non-existent value
Apple Pineapple false
Method 2: Using Object.entries() with find()
A more direct approach that doesn't create an intermediate object:
const products = {
"Pineapple": 38,
"Apple": 110,
"Pear": 109
};
const findKeyDirect = (obj, val) => {
const entry = Object.entries(obj).find(([key, value]) => value === val);
return entry ? entry[0] : false;
};
console.log(findKeyDirect(products, 110));
console.log(findKeyDirect(products, 109));
console.log(findKeyDirect(products, 999));
Apple Pear false
Method 3: Complete Reverse Mapping
Create a fully reverse-mapped object for multiple lookups:
const products = {
"Pineapple": 38,
"Apple": 110,
"Pear": 109
};
const createReverseMap = (obj) => {
const reverseMap = {};
for (const [key, value] of Object.entries(obj)) {
reverseMap[value] = key;
}
return reverseMap;
};
const reverseProducts = createReverseMap(products);
console.log(reverseProducts);
console.log(reverseProducts[110]);
console.log(reverseProducts[38]);
{ '38': 'Pineapple', '109': 'Pear', '110': 'Apple' }
Apple
Pineapple
Comparison
| Method | Performance | Memory Usage | Best For |
|---|---|---|---|
| Object.keys() + map() | O(n) + O(1) lookup | Creates intermediate object | Single lookups |
| Object.entries() + find() | O(n) per lookup | Low memory | Occasional lookups |
| Complete reverse mapping | O(n) + O(1) lookup | Stores reverse object | Multiple lookups |
Conclusion
Use Object.entries() with find() for occasional lookups, or create a complete reverse map for frequent value-to-key searches. Choose based on your performance and memory requirements.
