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 ?
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!
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.
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.
I'd use Lo-Dash.transform like this:
var lowerObj = _.transform(obj, function (result, val, key) { result[key.toLowerCase()] = val; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With