Convert returned JSON Object Properties to (lower first) camelCase

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

    This solution based on the plain js solution above, uses loadash and Keeps an array if passed as a parameter and Only change the Keys

    function camelCaseObject(o) {
        let newO, origKey, value
        if (o instanceof Array) {
            newO = []
            for (origKey in o) {
                value = o[origKey]
                if (typeof value === 'object') {
                    value = camelCaseObject(value)
                }
                newO.push(value)
            }
        } else {
            newO = {}
            for (origKey in o) {
                if (o.hasOwnProperty(origKey)) {
                    newO[_.camelCase(origKey)] = o[origKey]
                }
            }
        }
        return newO
    }
    
    // Example
    const obj = [
    {'my_key': 'value'},
     {'Another_Key':'anotherValue'},
     {'array_key':
       [{'me_too':2}]
      }
    ]
    console.log(camelCaseObject(obj))

提交回复
热议问题