Convert returned JSON Object Properties to (lower first) camelCase

后端 未结 18 2328
忘掉有多难
忘掉有多难 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:31

    Updated code using the reference from https://plnkr.co/edit/jtsRo9yU12geH7fkQ0WL?p=preview This handles the Objects with array with objects inside it too and so on, by keeping arrays as arrays (which you can iterate over using map)

    function snakeToCamelCase(snake_case_object){
      var camelCaseObject;
      if (isPlainObject(snake_case_object)) {        
        camelCaseObject = {};
      }else if(isArray(snake_case_object)){
        camelCaseObject = [];
      }
      forEach(
        snake_case_object,
        function(value, key) {
          if (isPlainObject(value) || isArray(value)) {
            value = snakeToCamelCase(value);
          }
          if (isPlainObject(camelCaseObject)) {        
            camelCaseObject[camelCase(key)] = value;
          }else if(isArray(camelCaseObject)){
            camelCaseObject.push(value);
          }
        }
      )
      return camelCaseObject;  
    }
    

提交回复
热议问题