分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

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

发布时间:2023-09-06 02:16责任编辑:郭大石关键词:js

一、题目示例:

思路:

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

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

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

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

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

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

二、实现代码

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]/glet 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对象属性名驼峰式转下划线

原文地址:https://www.cnblogs.com/detanx/p/JSObjBename.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved