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

前端 未结 20 2525
野性不改
野性不改 2020-12-04 20:42

I\'ve come up with

function keysToLowerCase (obj) {
  var keys = Object.keys(obj);
  var n = keys.length;
  while (n--) {
    var key = keys[n]; // \"cache\"         


        
20条回答
  •  旧巷少年郎
    2020-12-04 21:24

    Using forEach seems to be a bit quicker in my tests- and the original reference is gone, so deleting the new one will put it in reach of the g.c.

    function keysToLowerCase(obj){
        Object.keys(obj).forEach(function (key) {
            var k = key.toLowerCase();
    
            if (k !== key) {
                obj[k] = obj[key];
                delete obj[key];
            }
        });
        return (obj);
    }
    

    var O={ONE:1,two:2,tHree:3,FOUR:4,Five:5,SIX:{a:1,b:2,c:3,D:4,E:5}}; keysToLowerCase(O);

    /* returned value: (Object) */

    {
        five:5,
        four:4,
        one:1,
        six:{
            a:1,
            b:2,
            c:3,
            D:4,
            E:5
        },
        three:3,
        two:2
    }
    

提交回复
热议问题