Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way (most efficient) to turn all the keys of an object to lower case?

I've come up with

function keysToLowerCase (obj) {   var keys = Object.keys(obj);   var n = keys.length;   while (n--) {     var key = keys[n]; // "cache" it, for less lookups to the array     if (key !== key.toLowerCase()) { // might already be in its lower case version         obj[key.toLowerCase()] = obj[key] // swap the value to a new lower case key         delete obj[key] // delete the old key     }   }   return (obj); } 

But I'm not sure how will v8 behave with that, for instance, will it really delete the other keys or will it only delete references and the garbage collector will bite me later ?

Also, I created these tests, I'm hoping you could add your answer there so we could see how they match up.

EDIT 1: Apparently, according to the tests, it's faster if we don't check if the key is already in lower case, but being faster aside, will it create more clutter by ignoring this and just creating new lower case keys ? Will the garbage collector be happy with this ?

like image 576
João Pinto Jerónimo Avatar asked Sep 22 '12 00:09

João Pinto Jerónimo


People also ask

How to make the keys of the object with lowercase?

To lowercase all keys in an object, use the Object. keys() method to get an array of the object's keys. Call the reduce() method, passing it an empty object as the initial value and on each iteration lowercase the key, assign the key-value pair to the object and return the result. Copied!

Are object keys case sensitive?

While object properties are strings and they are case sensitive, you could use an own standard and use only lower case letters for the access. You could apply a String#toLowerCase to the key and use a function as wrapper for the access.


2 Answers

The fastest I come up with is if you create a new object:

var key, keys = Object.keys(obj); var n = keys.length; var newobj={} while (n--) {   key = keys[n];   newobj[key.toLowerCase()] = obj[key]; } 

I'm not familiar enough with the current inner working of v8 to give you a definitive answer. A few years ago I saw a video where the developers talked about objects, and IIRC it will only delete the references and let the garbage collector take care of it. But it was years ago so even if it was like that then, it doesn't need to be like that now.

Will it bite you later? It depends on what you are doing, but probably not. It is very common to create short lived objects so the code is optimized to handle it. But every environment has its limitations, and maybe it will bite you. You have to test with actual data.

like image 142
some Avatar answered Sep 22 '22 21:09

some


I'd use Lo-Dash.transform like this:

var lowerObj = _.transform(obj, function (result, val, key) {     result[key.toLowerCase()] = val; }); 
like image 21
caleb Avatar answered Sep 23 '22 21:09

caleb