[英]Rename Object Keys from Snake Case to Camel Case Recursively Without Using Lodash
如何使用普通的 javascript 遞歸地將 object 密鑰從蛇盒轉換為駱駝盒,而不依賴於 Lodash 等外部庫。 以下是僅適用於 object 第一級的嘗試。 最好的方法是什么?
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));
更新:添加了值為 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.
由於您也嵌套了 arrays,而不僅僅是嵌套對象。 如果找到,您必須通過renameKeys
測試它們和.map
每個項目。
您可能還想調整正則表達式,以便替換所有下划線,而不僅僅是那些后跟字母字符的下划線:
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));
要同時允許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));
如果 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));
為嵌套的 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 },
});
}, {});
你可以使用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))
我認為這種駱駝化嵌套 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.