formatting json data to be camelCased

前端 未结 5 1596
一整个雨季
一整个雨季 2021-02-13 13:57

I get a json response from the server that looks something like this:

{
    \"Response\": {
        \"FirstName\": \"John\",
        \"LastName\": \"Smith\",
            


        
5条回答
  •  一向
    一向 (楼主)
    2021-02-13 14:32

    Here is a functional recursive (ES6) approach.

    function convertKeysToCamelCase(o) {
      if (o === null || o === undefined) {
        return o;
      } else if (Array.isArray(o)) {
        return o.map(convertKeysToCamelCase);
      }
      return typeof o !== 'object' ? o : Object.keys(o).reduce((prev, current) => {
        const newKey = `${current[0].toLowerCase()}${current.slice(1)}`;
        if (typeof o[current] === 'object') {
          prev[newKey] = convertKeysToCamelCase(o[current]);
        } else {
          prev[newKey] = o[current];
        }
        return prev;
      }, {});
    }
    
    // successfully tested input
    const o = {
      SomeNum: 1,
      SomeStr: 'a',
      SomeNull: null,
      SomeUndefined: undefined,
      SomeBoolean: true,
      SomeNaN: NaN,
      NestedObject: {
        SomeSentence: 'A is for apple',
        AnotherNested: {
          B: 'is for blahblah'
        }
      },
      NumArray: [1, 2, 3, 4],
      StringArray: ['a', 'b', 'c'],
      BooleanArray: [true, false],
      ArrayOfArrays: [[1,2,], ['a','b']],
      ObjectArray: [{Foo:'bar'}, {Hello:'world', Nested:{In:'deep'}}],
      MixedArray: [1,'a', true, null, undefined, NaN, [{Foo:'bar'}, 'wat']]
    }
    
    const output = convertKeysToCamelCase(o);
    
    console.log(output.mixedArray[6][0].foo); // 'bar'
    

提交回复
热议问题