Created
August 4, 2018 00:49
-
-
Save wmcbain/4f1ff7fd78303259f66fdd327cc691c9 to your computer and use it in GitHub Desktop.
Python API responses with underscores to a sane camelCase response in JS π
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const camelCase = obj => { | |
let newObj = {} | |
for (let key in obj) { | |
const currentItem = obj[key] | |
if (!obj.hasOwnProperty(key)) continue | |
let newKey = key | |
while (newKey.includes('_')) { | |
newKey = newKey.replace(/_([a-z|1-9])/g, k => k[1].toUpperCase()) | |
} | |
let newItem | |
if (Array.isArray(currentItem)) { | |
const newArray = [] | |
for (let item of currentItem) { | |
newArray.push(camelCase(item)) | |
} | |
newItem = newArray | |
} else if (typeof currentItem === 'object') { | |
newItem = camelCase(currentItem) | |
} | |
newObj = { | |
...newObj, | |
[newKey]: newItem || currentItem | |
} | |
} | |
return newObj | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment