Convert returned JSON Object Properties to (lower first) camelCase

后端 未结 18 2275
忘掉有多难
忘掉有多难 2020-12-04 21:05

I have JSON returned from an API like so:

Contacts: [{ GivenName: "Matt", FamilyName: "Berry" }]

To keep this consistent

18条回答
  •  失恋的感觉
    2020-12-04 21:20

    You can do this with this recursive function (with lodash and ES6):

    import { camelCase } from 'lodash';
    
    const camelizeKeys = (obj) => {
      if (Array.isArray(obj)) {
        return obj.map(v => camelizeKeys(v));
      } else if (obj !== null && obj.constructor === Object) {
        return Object.keys(obj).reduce(
          (result, key) => ({
            ...result,
            [camelCase(key)]: camelizeKeys(obj[key]),
          }),
          {},
        );
      }
      return obj;
    };
    

    Test:

    const obj = {
      'FirstName': 'John',
      'LastName': 'Smith',
      'BirthDate': new Date(),
      'ArrayTest': ['one', 'TWO', 3],
      'ThisKey': {
        'This-Sub-Key': 42
      }
    }
    
    console.log(JSON.stringify(camelizeKeys(obj)))
    

    Output:

    {  
       "firstName": "John",
       "lastName": "Smith",
       "birthDate": "2018-05-31T09:03:57.844Z",
       "arrayTest":[  
          "one",
          "TWO",
          3
       ],
       "thisKey":{  
          "thisSubKey": 42
       }
    }
    

提交回复
热议问题