如何在嵌套对象中小写键



我有一个嵌套对象和嵌套键,我想把它们都变成小写:

let input : {
"KEY1" : "VALUE1",
"KEY2" : {"SUBKEY1":"SUBVALUE2"}
}

所以结果值result应该是

console.log(result)
{
"key1" : "VALUE1",
"key2" : {"subkey1":"SUBVALUE2"}
}

如何在嵌套对象中小写所有键?

我将使用递归。

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));

这是一个使用属性名的小写版本克隆对象的递归函数。

我试着让它也与数组工作,它会,因为那些仍然是对象,但我防止它列出长度属性。

我还考虑了一个用户在下面的评论中建议的空值。

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;
}

您可以遍历键并创建一个新对象

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);

最新更新