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
What's the most efficient way to turn all the keys of an object to lower case - JavaScript?
When working with JavaScript objects, you may need to convert all property keys to lowercase for consistency. Here's how to efficiently transform object keys using built-in JavaScript methods.
Sample Object
Let's start with an object that has uppercase keys:
var details = {
"STUDENTNAME": "John",
"STUDENTAGE": 21,
"STUDENTCOUNTRYNAME": "US"
};
console.log("Original object:", details);
Original object: { STUDENTNAME: 'John', STUDENTAGE: 21, STUDENTCOUNTRYNAME: 'US' }
Method 1: Using Object.keys() and while Loop
This approach uses a while loop to iterate through object keys and create a new object with lowercase keys:
var details = {
"STUDENTNAME": "John",
"STUDENTAGE": 21,
"STUDENTCOUNTRYNAME": "US"
};
var tempKey, allKeysOfDetails = Object.keys(details);
var numberOfKey = allKeysOfDetails.length;
var allKeysToLowerCase = {};
while (numberOfKey--) {
tempKey = allKeysOfDetails[numberOfKey];
allKeysToLowerCase[tempKey.toLowerCase()] = details[tempKey];
}
console.log("Lowercase keys:", allKeysToLowerCase);
Lowercase keys: { studentcountryname: 'US', studentage: 21, studentname: 'John' }
Method 2: Using Object.entries() and reduce() (More Efficient)
A more modern and concise approach using ES6 methods:
var details = {
"STUDENTNAME": "John",
"STUDENTAGE": 21,
"STUDENTCOUNTRYNAME": "US"
};
var lowercaseObject = Object.entries(details).reduce((acc, [key, value]) => {
acc[key.toLowerCase()] = value;
return acc;
}, {});
console.log("Using reduce:", lowercaseObject);
Using reduce: { studentname: 'John', studentage: 21, studentcountryname: 'US' }
Method 3: Using Object.fromEntries() (ES2019)
The most concise approach using the latest JavaScript features:
var details = {
"STUDENTNAME": "John",
"STUDENTAGE": 21,
"STUDENTCOUNTRYNAME": "US"
};
var lowercaseObject = Object.fromEntries(
Object.entries(details).map(([key, value]) => [key.toLowerCase(), value])
);
console.log("Using fromEntries:", lowercaseObject);
Using fromEntries: { studentname: 'John', studentage: 21, studentcountryname: 'US' }
Performance Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| while loop + Object.keys() | Medium | Fast | Excellent |
| reduce() + Object.entries() | Good | Medium | ES6+ |
| Object.fromEntries() + map() | Excellent | Medium | ES2019+ |
Conclusion
For maximum compatibility, use the while loop approach. For modern applications, Object.fromEntries() with map() provides the cleanest and most readable solution.
Advertisements
