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

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

    This is how I do it. My input can be anything and it recuses through nested objects as well as arrays of objects.

    const fixKeys = input => Array.isArray(input)
      ? input.map(fixKeys)
      : typeof input === 'object'
      ? Object.keys(input).reduce((acc, elem) => {
          acc[elem.toLowerCase()] = fixKeys(input[elem])
          return acc
        }, {})
      : input
    

    tested using mocha

    const { expect } = require('chai')
    
    const fixKeys = require('../../../src/utils/fixKeys')
    
    describe('utils/fixKeys', () => {
      const original = {
        Some: 'data',
        With: {
          Nested: 'data'
        },
        And: [
          'an',
          'array',
          'of',
          'strings'
        ],
        AsWellAs: [
          { An: 'array of objects' }
        ]
      }
    
      const expected = {
        some: 'data',
        with: {
          nested: 'data'
        },
        and: [
          'an',
          'array',
          'of',
          'strings'
        ],
        aswellas: [{ an: 'array of objects' }]
      }
    
      let result
    
      before(() => {
        result = fixKeys(original)
      })
    
      it('left the original untouched', () => {
        expect(original).not.to.deep.equal(expected)
      })
    
      it('fixed the keys', () => {
        expect(result).to.deep.equal(expected)
      })
    })
    

提交回复
热议问题