Skip to content

Instantly share code, notes, and snippets.

@sibu-github
Last active February 7, 2019 01:16
Show Gist options
  • Save sibu-github/a08c084ff64369f2f6a2b1ae6ee7f10d to your computer and use it in GitHub Desktop.
Save sibu-github/a08c084ff64369f2f6a2b1ae6ee7f10d 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 define reuturn
if (!str) {
return str;
}
let letters = str.split("");
let idx = letters.indexOf("_");
while (idx > -1) {
// if '_' is not first or last character
// then capitalize next character
if (idx !== 0 && letters.length > idx + 1) {
const nextLetter = letters[idx + 1];
letters[idx + 1] = nextLetter.toUpperCase();
}
// remove '_' character
letters.splice(idx, 1);
// get the index of next '_' character
idx = letters.indexOf("_");
}
// return str in camel case
return letters.join("");
}
// 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