码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2018-10-01 15:03:55      阅读:352      评论:0      收藏:0      [点我收藏+]

标签:数组   log   png   大写   ice   dex   赋值   cti   while   

一、题目示例:

思路:

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

标签:数组   log   png   大写   ice   dex   赋值   cti   while   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!