Convert returned JSON Object Properties to (lower first) camelCase

后端 未结 18 2268
忘掉有多难
忘掉有多难 2020-12-04 21:05

I have JSON returned from an API like so:

Contacts: [{ GivenName: "Matt", FamilyName: "Berry" }]

To keep this consistent

18条回答
  •  -上瘾入骨i
    2020-12-04 21:26

    Here's a reliable, recursive function that will properly camelCase all of a JavaScript object's properties:

    function toCamel(o) {
      var newO, origKey, newKey, value
      if (o instanceof Array) {
        return o.map(function(value) {
            if (typeof value === "object") {
              value = toCamel(value)
            }
            return value
        })
      } else {
        newO = {}
        for (origKey in o) {
          if (o.hasOwnProperty(origKey)) {
            newKey = (origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey).toString()
            value = o[origKey]
            if (value instanceof Array || (value !== null && value.constructor === Object)) {
              value = toCamel(value)
            }
            newO[newKey] = value
          }
        }
      }
      return newO
    }
    

    Test:

    var obj = {
      'FirstName': 'John',
      'LastName': 'Smith',
      'BirthDate': new Date(),
      'ArrayTest': ['one', 'TWO', 3],
      'ThisKey': {
        'This-Sub-Key': 42
      }
    }
    
    console.log(JSON.stringify(toCamel(obj)))
    

    Output:

    {
        "firstName":"John",
        "lastName":"Smith",
        "birthDate":"2017-02-13T19:02:09.708Z",
        "arrayTest": [
            "one", 
            "TWO", 
            3
        ],
        "thisKey":{
            "this-Sub-Key":42
        }
    }
    

提交回复
热议问题