Skip to content

Instantly share code, notes, and snippets.

@lesleh
Created March 31, 2020 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lesleh/79ee969b62b6fb905277803c8574b0f7 to your computer and use it in GitHub Desktop.
Save lesleh/79ee969b62b6fb905277803c8574b0f7 to your computer and use it in GitHub Desktop.
const isArray = function (a) {
return Array.isArray(a);
};
const isObject = function (o) {
return o === Object(o) && !isArray(o) && typeof o !== 'function';
};
const toCamel = s => (
s.replace(/([-_][a-z])/ig, $1 => $1.toUpperCase().replace(/[-_]/, ''))
);
const keysToCamel = (o) => {
if (isObject(o)) {
return Object.fromEntries(
Object.entries(o).map(([k, v]) => [toCamel(k), keysToCamel(v)]),
);
}
if (isArray(o)) {
return o.map(keysToCamel);
}
return o;
};
const o = {
foo_bar: 42,
something_else: [
{ this_also: {} },
{ works_with: {} },
{ arrays_of_objects: {} },
],
};
console.log(keysToCamel(o));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment