Skip to content

Instantly share code, notes, and snippets.

@orcaman
Last active January 26, 2021 10:32
Show Gist options
  • Save orcaman/dd40b04e0e42eed841d7 to your computer and use it in GitHub Desktop.
Save orcaman/dd40b04e0e42eed841d7 to your computer and use it in GitHub Desktop.
Get a lowercase representation of a JSON object, recursively (JS)
function toLowerCase(obj) {
if (!obj) {
return;
}
if (typeof obj !== 'Object' && typeof obj !== 'object') {
return;
}
var keys = Object.keys(obj);
var result = {};
keys.map(function(k, v) {
if (typeof k === 'string') {
if (typeof obj[k] === 'string') {
result[k.toLowerCase()] = obj[k].toLowerCase();
} else {
// if the node is an object, perform the same process over that node
if (typeof obj[k] === 'Object' || typeof obj[k] === 'object') {
result[k.toLowerCase()] = toLowerCase(obj[k]);
} else {
result[k.toLowerCase()] = obj[k];
}
}
}
});
return result;
}
@Crashillo
Copy link

Great work!
I'd suggest to remove the toLowerCase() function for object values result[k.toLowerCase()] = obj[k]; to keep the original ones, only modifying the structure. Or even better, add an optional boolean flag function toLowerCase(obj, force) to preserve or replace object values.

@sulenchy
Copy link

Thanks. This actually saves my time.

@dipenparmar12
Copy link

Thanks friend..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment