<p>I came up with the following solution</p>
<pre class="brush:php;toolbar:false;">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()) { // May already be lowercase
obj[key.toLowerCase()] = obj[key] // Swap the value to the new lowercase key
delete obj[key] // Delete the old key
}
}
return (obj);
}</pre>
<p>But I'm not sure how v8 will handle it, e.g. will it actually delete other keys or will it just delete the reference and then the garbage collector will bite me in the back? </p>
<p>Also, I created these tests and would love for you to add your answers there so we can see how they match up. </p>
Does this create more confusion? Will the garbage collector be happy with this? </p>
Using
Object.fromEntries
(ES10)Local and immutable solution using the new
Object.fromEntries
method:Until this function is widely available , you can use the following polyfill custom definition:
One benefit is that this method is the opposite of
Object.entries
, so now you can switch back and forth between object and array representations.The fastest way I can think of is to create a new object:
I'm not familiar enough with the current inner workings of v8 to give a clear answer. A few years ago I saw a video where a developer discussed objects and if I remember correctly it just removes the reference and lets the garbage collector deal with it. But that was a few years ago, so even if it was true then, it's not necessarily true now.
Will it cause you trouble later? It depends on what you are doing, but probably not. Creating ephemeral objects is very common, so code is optimized to handle it. But every environment has its limitations and maybe it will cause you trouble. You have to test with actual data.