[英]Rename Object Keys from Snake Case to Camel Case Recursively Without Using Lodash
How to recursively convert object keys from snake case to camel case using plain javascript without relying on external libraries such as Lodash.如何使用普通的 javascript 递归地将 object 密钥从蛇盒转换为骆驼盒,而不依赖于 Lodash 等外部库。 Below is an attempt that only works for first level of the object.
以下是仅适用于 object 第一级的尝试。 What's the best way to do this?
最好的方法是什么?
const obj = {
key_first: 'firstVal',
key_second: 'secondVal',
key_third: null,
nested_obj: {
nested_one: 'nested 1 value',
nested_two: 'nested 2 value'
},
nested_arr: [{
nested_obj_one: 'nested obj val 1'
}, {
nested_obj_two: 'nested obj val 2'
}, {
level_3_nested: [{
level_3_key: 'level 3 value',
level_3_another_key: 'another level 3 value'
}]
}]
};
const renameKeys = obj => Object
.entries(obj)
.reduce((acc, [key, val]) => {
const modifiedKey = key.replace(/_([a-z])/g, g => g[1].toUpperCase());
return ({
...acc,
...{ [modifiedKey]: val },
});
}, {});
console.log(renameKeys(obj));
Update: Added key with value of null.更新:添加了值为 null 的键。
I'd .map
the Object.entries
, replacing the key in the entry, while recursively calling renamekeys
on the value, and pass the whole array entry to Object.fromEntries
to turn it back into an object. I'd
.map
the Object.entries
, replacing the key in the entry, while recursively calling renamekeys
on the value, and pass the whole array entry to Object.fromEntries
to turn it back into an object.
Since you have nested arrays too, not just nested objects.由于您也嵌套了 arrays,而不仅仅是嵌套对象。 you'll have to test for them and
.map
each item via renameKeys
if found.如果找到,您必须通过
renameKeys
测试它们和.map
每个项目。
You also probably want to tweak the regex so that all underscores get replaced, not just those followed by alphabetical characters:您可能还想调整正则表达式,以便替换所有下划线,而不仅仅是那些后跟字母字符的下划线:
const obj = { key_first: 'firstVal', key_second: 'secondVal', nested_obj: { nested_one: 'nested 1 value', nested_two: 'nested 2 value' }, nested_arr: [{ nested_obj_one: 'nested obj val 1' }, { nested_obj_two: 'nested obj val 2' }, { level_3_nested: [{ level_3_key: 'level 3 value', level_3_another_key: 'another level 3 value' }] }] }; const processVal = val => ( typeof val?== 'object': val. Array?isArray(val). val:map(renameKeys); renameKeys(val) ). const renameKeys = obj => Object.fromEntries( Object.entries(obj),map(([key. val]) => [ key.replace(/_(,)/g. g => g[1],toUpperCase()); processVal(val) ]) ). console;log(renameKeys(obj));
To permit null
values as well:要同时允许
null
值:
const obj = { key_first: 'firstVal', key_second: 'secondVal', nested_obj: { nested_one: 'nested 1 value', nested_two: 'nested 2 value' }, nested_arr: [{ nested_obj_one: 'nested obj val 1' }, { nested_obj_two: 'nested obj val 2' }, { level_3_nested: [{ level_3_key: 'level 3 value', level_3_another_key: 'another level 3 value' }] }] }; const processVal = val => ( (typeof val?== 'object' || val === null): val. Array?isArray(val). val:map(renameKeys); renameKeys(val) ). const renameKeys = obj => Object.fromEntries( Object.entries(obj),map(([key. val]) => [ key.replace(/_(,)/g. g => g[1],toUpperCase()); processVal(val) ]) ). console;log(renameKeys(obj));
If the arrays can be on the first level, then use val.map(processVal)
in processVal
, and first call processVal
instead of renameKeys
:如果 arrays 可以在第一级,则在 processVal 中使用
val.map(processVal)
processVal
并首先调用processVal
而不是renameKeys
:
const obj = { simple_arr: ['a1', 'b1', 'c1'], key_first: 'firstVal', key_second: 'secondVal', nested_obj: { nested_one: 'nested 1 value', nested_two: 'nested 2 value' }, nested_arr: [{ nested_obj_one: 'nested obj val 1' }, { nested_obj_two: 'nested obj val 2' }, { level_3_nested: [{ level_3_key: 'level 3 value', level_3_another_key: 'another level 3 value' }] }] }; const processVal = val => ( (typeof val?== 'object' || val === null): val. Array?isArray(val). val:map(processVal); renameKeys(val) ). const renameKeys = obj => Object.fromEntries( Object.entries(obj),map(([key. val]) => [ key.replace(/_(,)/g. g => g[1],toUpperCase()); processVal(val) ]) ). console;log(processVal(obj));
Add recursive call for nested object为嵌套的 object 添加递归调用
const renameKeys = obj => Object
.entries(obj)
.reduce((acc, [key, val]) => {
const modifiedKey = key.replace(/_([a-z])/g, g => g[1].toUpperCase());
const modifiedVal = typeof val === 'object' && val !== null ?
renameKeys(val) : val;
return ({
...acc,
...{ [modifiedKey]: modifiedVal },
});
}, {});
You can use for..in
something like this你可以使用
for..in
这样的东西
const obj = {key_first: 'firstVal',key_second: 'secondVal',nested_obj: {nested_one: 'nested 1 value',nested_two: 'nested 2 value'},nested_arr: [{nested_obj_one: 'nested obj val 1'}, {nested_obj_two: 'nested obj val 2'}, {level_3_nested: [{level_3_key: 'level 3 value',level_3_another_key: 'another level 3 value'}]}]}; let keyChanger = (obj) => { for (let key in obj) { if (typeof obj[key] === 'object') { if (Array.isArray(obj[key])) { obj[key].map(v => keyChanger(v)) } else { keyChanger(obj[key]) } } const modifiedKey = key.replace(/_([az])/g, g => g[1].toUpperCase()); obj[modifiedKey] = obj[key] delete obj[key] } return obj } console.log(keyChanger(obj))
I think this method of camelizing nested object keys will save lot of iterations.我认为这种骆驼化嵌套 object 键的方法将节省大量迭代。
const camelizeNestedKeys = function(dataObj) { return JSON.parse(JSON.stringify(dataObj).trim().replace(/("\w+":)/g, function(keys) { return keys.replace(/(.(\_|-|\s)+.)/g, function(subStr) { return subStr[0]+(subStr[subStr.length-1].toUpperCase()); }) })); } const data = { 'id':'123', 'employee_name': 'John', 'employee_type': 'new' }; const nestedData = { 'id':'123', 'employee_name': 'John', 'employee_type': 'new', 'exployee_projects': [ {"project_name": "test1", "project_year": 2004}, {"project_name": "test2", "project_year": 2004} ] }; console.log(camelizeNestedKeys(data)); console.log(camelizeNestedKeys(nestedData));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.