Last active
November 2, 2020 16:20
-
-
Save andrhamm/28fbddd3d425a3d6888ab5898e3dec41 to your computer and use it in GitHub Desktop.
Javascript Deep Change Key Case
This file contains hidden or 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
// deeply changes the case of object keys, including in sub arrays of objects | |
const _ = require('lodash'); | |
function deepChangeKeyCase(value, fn) { | |
if (Array.isArray(value)) { | |
return value.map(v => deepChangeKeyCase(v, fn)); | |
} else if (_.isPlainObject(value)) { | |
return Object.entries(value).reduce((acc, [k, v]) => { | |
acc[fn(k)] = deepChangeKeyCase(v, fn); | |
return acc; | |
}, {}); | |
} | |
return value; | |
} | |
// example usage | |
function camelCaseObj(value) { | |
return deepChangeKeyCase(value, _.camelCase); | |
} | |
function snakeCaseObj(value) { | |
return deepChangeKeyCase(value, _.snakeCase); | |
} |
This file contains hidden or 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
// or as a lodash mixin | |
_.mixin({ | |
deepChangeKeyCase: (value, fn) => { | |
if (_.isArray(value)) { | |
return value.map(v => _.deepChangeKeyCase(v, fn)); | |
} else if (_.isPlainObject(value)) { | |
return Object.entries(value).reduce((acc, [k, v]) => { | |
acc[fn(k)] = _.deepChangeKeyCase(v, fn); | |
return acc; | |
}, {}); | |
} | |
return value; | |
}, | |
}); | |
// example usage | |
_.deepChangeKeyCase(myObj, _.snakeCase) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment