What's the most efficient way to turn all the keys of an object to lower case - JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Let’s say the following is our object −

var details =
{
   "STUDENTNAME": "John",
   "STUDENTAGE": 21,
   "STUDENTCOUNTRYNAME": "US"
}

As you can see above, the keys are in capital case. We need to turn all these keys to lower case. Use toLowerCase() for this.

Example

Following is the code −

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(allKeysToLowerCase);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo297.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo297.js
{ studentcountryname: 'US', studentage: 21, studentname: 'John' }
raja
Published on 09-Nov-2020 10:35:30
Advertisements