zoukankan      html  css  js  c++  java
  • 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]/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}
    

      

  • 相关阅读:
    20200302 数据分析之numpy以及Jupyter
    20200228 scrapy高级使用及分布式
    20200226 请求库selenium
    20200224 爬虫-requests模块
    0219 请求上下文解析与g对象
    Matlab矩阵求导和求梯度有什么不同
    矩阵中范数的处理方式
    如何巧妙地使用递归
    遗传算法求最短路径
    nparray的维度和取值方式
  • 原文地址:https://www.cnblogs.com/detanx/p/JSObjBename.html
Copyright © 2011-2022 走看看