I have a nested object with nested keys that I would like to make all lowercase:
let input : {
"KEY1" : "VALUE1",
"KEY2" : {"SUBKEY1":"SUBVALUE2"}
}
So the resulting value result should be:
console.log(result)
{
"key1" : "VALUE1",
"key2" : {"subkey1":"SUBVALUE2"}
}
How to lowercase all the keys in a nested object?
I would use recursion here.
const input = {
"KEY1": "VALUE1",
"KEY2": {"SUBKEY1": "SUBVALUE2"},
"KEY3": {"SUBKEY2": {"SUBSUBKEY1": "HELLO WORLD!"}},
"KEY4": null
};
function isPlainObject(input) {
return input && !Array.isArray(input) && typeof input === 'object';
}
function propertyNamesToLowercase(obj) {
const final = {};
// Iterate over key-value pairs of the root object 'obj'
for (const [key, value] of Object.entries(obj)) {
// Set the lowercased key in the 'final' object and use the original value if it's not an object
// else use the value returned by this function (recursive call).
final[key.toLowerCase()] = isPlainObject(value) ? propertyNamesToLowercase(value) : value;
}
return final;
}
console.log(propertyNamesToLowercase(input));
This is a recursive function cloning an object while using the lowercase version of its property names.
I tried to make it work also with arrays and it will since those are still objects but I prevent it to list the length property.
I also considered the null value as suggested by a user in comments below.
let input = {
"KEY1" : "VALUE1",
"KEY2" : {"SUBKEY1":"SUBVALUE2"},
"KEY3" : [
{
"KEY4" : 'value',
},
2,
],
"KEY4" : null,
}
const clone = cloneObject(input);
console.log(clone);
function cloneObject(o){
if (o === null)
return null;
const clone = {};
for(k of Object.getOwnPropertyNames(o)){
if( Array.isArray(o) && k === 'length')
continue;
newPropertyName = k.toLowerCase();
clone[newPropertyName] = (typeof o[k] === 'object') ? cloneObject(o[k]) : o[k];
delete o[k];
}
return clone;
}
You can iterate through the keys and make a new object
const result = Object.keys(input).map((currentKey) => {
const newKey = currentKey.toLowerCase(); // generating a new key
return { newKey: input[currentKey]} // building a new object entry for all the keys
})
console.log(result);