javascript 解決後端返回的數據是下劃線命名規範而前端需要的是駝峯命名規範
一.初級版本
僅支持兩個下劃線:
例如:user_name , user_id, .....
//下劃線轉駝峯 export const toTuofeng = (str: string) => { return str.replace(/"(\w)+":/g, (all) => { if (all.indexOf('_') === -1) { return all } return ( all.split('_')[0] + all.split('_')[1].slice(0, 1).toUpperCase() + all.split('_')[1].slice(1) ) }) }
升級版本
支持多個下劃線:
例如:user_name_test user_name_test1_test2 。。。。
// json的key下劃線轉駝峯 export const toTuofeng = (str: string) => { return str.replace(/"(\w)+":/g, (all) => { if (all.indexOf('_') === -1) { return all } let strNew= '' all.split('_').forEach((element, index) => { if (index <= 0) { strNew+= element } else { strNew+= element.slice(0, 1).toUpperCase() + element.slice(1) } }) return str1 }) }