Convert returned JSON Object Properties to (lower first) camelCase

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

    To change a plain object's keys from snake_case to camelCase recursively try the following
    (which uses Lodash):

    function objectKeysToCamelCase(snake_case_object) {
      var camelCaseObject = {};
      _.forEach(
        snake_case_object,
        function(value, key) {
          if (_.isPlainObject(value) || _.isArray(value)) {     // checks that a value is a plain object or an array - for recursive key conversion
            value = objectKeysToCamelCase(value);               // recursively update keys of any values that are also objects
          }
          camelCaseObject[_.camelCase(key)] = value;
        }
      )
      return camelCaseObject;
    };
    

    test in this PLUNKER

    Note: also works recursively for objects within arrays

提交回复
热议问题