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

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

    Simplified Answer

    For simple situations, you can use the following example to convert all keys to lower case:

    Object.keys(example).forEach(key => {
      const value = example[key];
      delete example[key];
      example[key.toLowerCase()] = value;
    });
    

    You can convert all of the keys to upper case using toUpperCase() instead of toLowerCase():

    Object.keys(example).forEach(key => {
      const value = example[key];
      delete example[key];
      example[key.toUpperCase()] = value;
    });
    

提交回复
热议问题