Skip to content

Instantly share code, notes, and snippets.

@teyc
Forked from sibu-github/convertToCamelCase.js
Last active February 7, 2019 01:18
Show Gist options
  • Save teyc/92d6dc37f3b8dd488a2c1162edf67194 to your computer and use it in GitHub Desktop.
Save teyc/92d6dc37f3b8dd488a2c1162edf67194 to your computer and use it in GitHub Desktop.
convert a JSON keys to camel case
// convert a key string to camelcase
function toCamelCase(str) {
// when str is not defined reuturn
if (!str) {
return str;
}
return str.charAt(0).toLowerCase() + str.substring(1);
}
// convert all keys in a json to camelcase
// NOTE: JSON parsing is not done here
// so before calling this function JSON should be parsed
function convertToCamelCase(json) {
// check if it is an array
if (Array.isArray(json)) {
return json.map(el => convertToCamelCase(el));
}
// check if it is an object
if (typeof json === "object") {
let newJson = { ...json };
Object.keys(newJson).forEach(key => {
// convert the key to camel case
const newKey = toCamelCase(key);
// copy the converted value of this key to a new variable
const value = convertToCamelCase(newJson[key]);
// remove the key from the json
delete newJson[key];
// replace the value under new converted key
newJson[newKey] = value;
});
return newJson;
}
// if it is not object or array
// then return as it is
return json;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment