search

Home  >  Q&A  >  body text

What is the most efficient way to convert all keys of an object to lowercase?

<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粉066224086P粉066224086477 days ago566

reply all(2)I'll reply

  • P粉792026467

    P粉7920264672023-08-23 10:44:49

    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.

    reply
    0
  • P粉258788831

    P粉2587888312023-08-23 00:25:13

    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.

    reply
    0
  • Cancelreply