Convert returned JSON Object Properties to (lower first) camelCase

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

提交回复
热议问题