formatting json data to be camelCased

前端 未结 5 1593
一整个雨季
一整个雨季 2021-02-13 13:57

I get a json response from the server that looks something like this:

{
    \"Response\": {
        \"FirstName\": \"John\",
        \"LastName\": \"Smith\",
            


        
5条回答
  •  鱼传尺愫
    2021-02-13 14:13

    @adamjyee Your solution works except for nested array of integers. A small fix could be:

    function convertKeysToCamelCase (o) {
        if (o === null) {
          return null
        } else if (o === undefined) {
          return undefined
        } else if (typeof o === 'number') {
          return o
        } else if (Array.isArray(o)) {
          return o.map(convertKeysToCamelCase)
        }
        return Object.keys(o).reduce((prev, current) => {
          const newKey = `${current[0].toLowerCase()}${current.slice(1)}`
          if (typeof o[current] === 'object') {
            prev[newKey] = convertKeysToCamelCase(o[current])
          } else {
            prev[newKey] = o[current]
          }
          return prev
        }, {})
    

    [Right to comment but lacking comment priviledge :(]

提交回复
热议问题