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

前端 未结 20 2587
野性不改
野性不改 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:29

    Here's my recursive version based on one of the above examples.

    //updated function
    var lowerObjKeys = function(obj) {
      Object.keys(obj).forEach(function(key) {
        var k = key.toLowerCase();
        if (k != key) {
          var v = obj[key]
          obj[k] = v;
          delete obj[key];
    
          if (typeof v == 'object') {
            lowerObjKeys(v);
          }
        }
      });
    
      return obj;
    }
    
    //plumbing
    console = {
      _createConsole: function() {
        var pre = document.createElement('pre');
        pre.setAttribute('id', 'console');
        document.body.insertBefore(pre, document.body.firstChild);
        return pre;
      },
      info: function(message) {
        var pre = document.getElementById("console") || console._createConsole();
        pre.textContent += ['>', message, '\n'].join(' ');
      }
    };
    
    //test case
    console.info(JSON.stringify(lowerObjKeys({
      "StackOverflow": "blah",
      "Test": {
        "LULZ": "MEH"
      }
    }), true));

    Beware, it doesn't track circular references, so you can end up with an infinite loop resulting in stack overflow.

提交回复
热议问题