Skip to content

Instantly share code, notes, and snippets.

@wmcbain
Created August 4, 2018 00:49
Show Gist options
  • Save wmcbain/4f1ff7fd78303259f66fdd327cc691c9 to your computer and use it in GitHub Desktop.
Save wmcbain/4f1ff7fd78303259f66fdd327cc691c9 to your computer and use it in GitHub Desktop.
Python API responses with underscores to a sane camelCase response in JS 😊
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