最近找了好久,对象转驼峰,驼峰转对象的方法。有考虑过把对象转成字符串,再通过正则匹配转化,但考虑到属性值里面也有下划线,所以使用递归的方法。
/**
* 字符串下划线转驼峰
*/
global.toCamelCaseVar =function (variable) {
return variable.replace(/\_+[a-zA-Z]/g, function (str, index) {
return index ? str.substr(-1).toUpperCase() : str
})
}
/**
* 对象key值驼峰转下划线
* @param obj
* @returns {*}
*/
global.objToKebaseCase =function (obj) {
var newObj =null,
regx =/[A-Z]/g;
if (typeof obj ==='object') {
if (!obj)return;
newObj = Object.prototype.toString.call(obj).slice(8, -1).toLowerCase().indexOf('array') > -1 ? [] : {};
for (let xin obj) {
let key = x.toString().replace(regx, function (word) {
return '_' + word.toLowerCase();
});
if (typeof obj[x] ==='object') {
newObj[key] = objToKebaseCase(obj[x]);
}else {
newObj[key] = obj[x];
}
}
}
return newObj;
}
/**
* 对象key值下划线转驼峰
* @param obj
* @returns {*}
*/
global.objToCamelCase =function (obj) {
var newObj =null;
if (typeof obj ==='object') {
if (!obj)return;
newObj = Object.prototype.toString.call(obj).slice(8, -1).toLowerCase().indexOf('array') > -1 ? [] : {};
for (let xin obj) {
let key = toCamelCaseVar(x.toString());
if (typeof obj[x] ==='object') {
newObj[key] = objToCamelCase(obj[x]);
}else {
newObj[key] = obj[x];
}
}
}
return newObj;
}