What is the most efficient way to convert all keys of an object to lowercase?
P粉066224086
P粉066224086 2023-08-22 12:42:40
0
2
571
<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>

P粉066224086
P粉066224086

reply all(2)
P粉792026467

Using Object.fromEntries (ES10)

Local and immutable solution using the new Object.fromEntries method:

const newObj = Object.fromEntries(
  Object.entries(obj).map(([k, v]) => [k.toLowerCase(), v])
);

Until this function is widely available , you can use the following polyfill custom definition:

Object.fromEntries = arr => Object.assign({}, ...Array.from(arr, ([k, v]) => ({[k]: v}) ));

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.

P粉258788831

The fastest way I can think of is to 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 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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template