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

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

    For all values:

    to_lower_case = function(obj) {
        for (var k in obj){
            if (typeof obj[k] == "object" && obj[k] !== null)
                to_lower_case(obj[k]);
            else if(typeof obj[k] == "string") {
                obj[k] = obj[k].toLowerCase();
            }
        }
        return obj;
    }
    

    Same can be used for keys with minor tweaks.

    0 讨论(0)
  • 2020-12-04 21:21

    The loDash/fp way, quite nice as its essentially a one liner

    import {
    mapKeys
    } from 'lodash/fp'
    
    export function lowerCaseObjectKeys (value) {
    return mapKeys(k => k.toLowerCase(), value)
    }
    
    0 讨论(0)
  • 2020-12-04 21:24

    I'd use Lo-Dash.transform like this:

    var lowerObj = _.transform(obj, function (result, val, key) {
        result[key.toLowerCase()] = val;
    });
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-04 21:24
    const keysToLowerCase = object => {
      return Object.keys(object).reduce((acc, key) => {
        let val = object[key];
        if (typeof val === 'object') {
          val = keysToLowerCase(val);
        }
        acc[key.toLowerCase()] = val;
        return acc;
      }, {});
    };
    

    Works for nested object.

    0 讨论(0)
  • 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;
    });
    
    0 讨论(0)
提交回复
热议问题