Convert returned JSON Object Properties to (lower first) camelCase

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

    Building on goredwards answer (which didn't handle the array fields correctly)

    function objectKeysToCamelCase(snake_case_object) {
      let camelCaseObject = {}
      _.forEach(
        snake_case_object,
        function(value, key) {
          if (_.isPlainObject(value)) {
            value = objectKeysToCamelCase(value)
          } else if (_.isArray(value)) {
            value = value.map(v => _.isPlainObject(v) ? objectKeysToCamelCase(v) : v)
          }
          camelCaseObject[_.camelCase(key)] = value
        },
      )
      return camelCaseObject
    }
    
    0 讨论(0)
  • 2020-12-04 21:40

    Took the challenge with lodash and some es6+ features Here is my implementation with the reduce function.

    function deeplyToCamelCase(obj) {
      return _.reduce(obj, (camelCaseObj, value, key) => {
        const convertedDeepValue = _.isPlainObject(value) || _.isArray(value)
          ? deeplyToCamelCase(value)
          : value;
        return { ...camelCaseObj, [_.camelCase(key)] : convertedDeepValue };
      }, {});
    };
    
    0 讨论(0)
  • 2020-12-04 21:40

    Use lodash ...

    function isPrimitive (variable) {
      return Object(variable) !== variable
    }
    
    function toCamel (variable) {
      if (isPrimitive(variable)) {
        return variable
      }
    
      if (_.isArray(variable)) {
        return variable.map(el => toCamel(el))
      }
    
      const newObj = {}
      _.forOwn(variable, (value, key) => newObj[_.camelCase(key)] = toCamel(value))
    
      return newObj
    }

    0 讨论(0)
  • 2020-12-04 21:40

    Convert object keys to camelCase with deep.

    import _ from 'lodash';
    
    export function objectKeysToCamelCase(entity) {
        if (!_.isObject(entity)) return entity;
    
        let result;
    
        result = _.mapKeys(entity, (value, key) => _.camelCase(key));
        result = _.mapValues(result, (value) => objectKeysToCamelCase(value));
    
        return result;
    }
    
    0 讨论(0)
  • 2020-12-04 21:42

    Using lodash and ES6, this will replace all keys recursively to camelcase:

    Shorthand:

    const camelCaseKeys = (obj) => ((!_.isObject(obj) && obj) || (_.isArray(obj) && obj.map((v) => camelCaseKeys(v))) || _.reduce(obj, (r, v, k) => ({ ...r, [_.camelCase(k)]: camelCaseKeys(v) }), {}));
    

    Expanded:

    const camelCaseKeys = (obj) => {
      if (!_.isObject(obj)) {
        return obj;
      } else if (_.isArray(obj)) {
        return obj.map((v) => camelCaseKeys(v));
      }
      return _.reduce(obj, (r, v, k) => {
        return { 
          ...r, 
          [_.camelCase(k)]: camelCaseKeys(v) 
        };
      }, {});
    };      
    
    0 讨论(0)
  • 2020-12-04 21:42

    Well I took up the challenge and think I figured it out:

    var firstToLower = function(str) {
        return str.charAt(0).toLowerCase() + str.slice(1);
    };
    
    var firstToUpper = function(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    };
    
    var mapToJsObject = function(o) {
        var r = {};
        $.map(o, function(item, index) {
            r[firstToLower(index)] = o[index];
        });
        return r;
    };
    
    var mapFromJsObject = function(o) {
        var r = {};
        $.map(o, function(item, index) {
            r[firstToUpper(index)] = o[index];
        });
        return r;
    };
    
    
    // Map to
    var contacts = [
        {
            GivenName: "Matt",
            FamilyName: "Berry"
        },
        {
            GivenName: "Josh",
            FamilyName: "Berry"
        },
        {
            GivenName: "Thomas",
            FamilyName: "Berry"
        }
    ];
    
    var mappedContacts = [];
    
    $.map(contacts, function(item) {
        var m = mapToJsObject(item);
        mappedContacts.push(m);
    });
    
    alert(mappedContacts[0].givenName);
    
    
    // Map from
    var unmappedContacts = [];
    
    $.map(mappedContacts, function(item) {
        var m = mapFromJsObject(item);
        unmappedContacts.push(m);
    });
    
    alert(unmappedContacts[0].GivenName);
    

    Property converter (jsfiddle)

    The trick is handling the objects as arrays of object properties.

    0 讨论(0)
提交回复
热议问题