javascript 解决后端返回的数据是下划线命名规范而前端需要的是驼峰命名规范

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
  })
}
posted @ 2022-07-10 22:08  土豆哥  阅读(685)  评论(0编辑  收藏  举报