Skip to main content

驼峰化

key 驼峰化

把对象中所有 key

下划线转驼峰

生成新对象

function isObject(obj) {
return Object.prototype.toString.call(obj) === "[object Object]";
}
function transfer(originObj) {
// 函数首次调用判断
if (!isObject(originObj)) return originObj;

// 新复制一个对象,我们返回这个
const result = {};

const reg = /_{1,2}\w/g; // 这里正则的格式取决于自己
// 该正则表达式可以用于查找以1到2个下划线开头,并紧跟**一个字母或数字**的子字符串,
const keys = Object.keys(originObj);
for (let key of keys) {
const value = originObj[key];
key = key.replace(reg, (match) =>
//_a -> A
match.replace(/_/g, "").toLocaleUpperCase()
);
result[key] = isObject(value) ? transfer(value) : value;
}

return result;
}