一、题目示例:

思路:

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

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

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

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

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

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

二、实现代码

  1. let obj = {Id1: 1, idName1: 2, idAgeName1: 3};
  2. let arr = []
  3. function strReplace(str) {
  4. const UP_CASE_REG =/[A-Z]/g;
  5. const NUMBER_REG=/[A-Za-z][\d]/g
  6. let newstr = ""
  7. getIndex(UP_CASE_REG, str)
  8. getIndex(NUMBER_REG, str)
  9. arr.sort((a,b)=> a-b )
  10. for(let i = 0;i < arr.length; i ++) {
  11. if(i === 0) {
  12. newstr += str.slice(0,arr[i]) + "_"
  13. }
  14. else {
  15. newstr += str.slice(arr[i-1],arr[i]) + "_"
  16. }
  17. }
  18. newstr += str.slice(arr[arr.length-1])
  19. return newstr.toLowerCase()
  20. }
  21. function getIndex(reg, str) {
  22. do{
  23. reg.test(str)
  24. if(reg.lastIndex !== 0 && reg.lastIndex-1 !== 0){//reg.lastIndex-1 !== 0判断首字母是否大写
  25. arr.push(reg.lastIndex-1)
  26. }
  27. }while(reg.lastIndex > 0)
  28. }
  29.  
  30. function strAllReplace(obj) {
  31. let newObj = {}
  32. Object.entries(obj).forEach(([key, value]) =>
  33. {
  34. newObj[strReplace(key)] = value
  35. arr = []
  36. })
  37. return newObj
  38. }
  39. console.log(strAllReplace(obj))//{id_1: 1, id_name_1: 2, id_age_name_1: 3}

  

 

版权声明:本文为detanx原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/detanx/p/JSObjBename.html