js对象属性名驼峰式转下划线

时间:2023-03-09 18:54:32
js对象属性名驼峰式转下划线

一、题目示例:

思路:

1、匹配属性名字符串中的大写字母和数字

2、通过匹配后的lastIndex属性获取匹配到的大写字母和数字的位置

3、判断大写字母的位置是否为首位置以及lastIndex是否为0,为0则表示匹配结束

4、将存放位置的数组进行从小到大排序,排序后将属性名按照字符串的slice方法切割并使用下划线重组

5、遍历对象的属性名并使用函数改变为新的命名,从新赋值到新的对象上(也可以使用改变对象的ES6新语法)

6、注意,每次在调用函数后,需要清空之前存放位置的数组

js对象属性名驼峰式转下划线

二、实现代码

let obj = {Id1: 1, idName1: 2, idAgeName1: 3};
let arr = []
function strReplace(str) {
const UP_CASE_REG =/[A-Z]/g;
const NUMBER_REG=/[A-Za-z][\d]/g
let newstr = ""
getIndex(UP_CASE_REG, str)
getIndex(NUMBER_REG, str)
arr.sort((a,b)=> a-b )
for(let i = 0;i < arr.length; i ++) {
if(i === 0) {
newstr += str.slice(0,arr[i]) + "_"
}
else {
newstr += str.slice(arr[i-1],arr[i]) + "_"
}
}
newstr += str.slice(arr[arr.length-1])
return newstr.toLowerCase()
}
function getIndex(reg, str) {
do{
reg.test(str)
if(reg.lastIndex !== 0 && reg.lastIndex-1 !== 0){//reg.lastIndex-1 !== 0判断首字母是否大写
arr.push(reg.lastIndex-1)
}
}while(reg.lastIndex > 0)
} function strAllReplace(obj) {
let newObj = {}
Object.entries(obj).forEach(([key, value]) =>
{
newObj[strReplace(key)] = value
arr = []
})
return newObj
}
console.log(strAllReplace(obj))//{id_1: 1, id_name_1: 2, id_age_name_1: 3}

  js对象属性名驼峰式转下划线