字符串 小驼峰格式转为下划线格式
function stringHumpTurn(val) {
return val.replace(/([A-Z])/g, "-$1").toLowerCase()
}
let s = "htmlCssJs";
console.log(stringHumpTurn(s), '字符串 小驼峰格式转为下划线格式');
字符串 下划线格式转为小驼峰格式
function stringConnectorTurn(val) {
if (val.indexOf("-") != -1) {
return val.replace(/-([a-z])/g, (p, m) => m.toUpperCase())
}
if (val.indexOf("_") != -1) {
return val.replace(/_([a-z])/g, (p, m) => m.toUpperCase())
}
return val
}
let s1 = "foo_style_css";
console.log(stringConnectorTurn(s1), '字符串_ 下划线格式转为小驼峰格式');
let s2 = "foo-style-css";
console.log(stringConnectorTurn(s2), '字符串- 下划线格式转为小驼峰格式');
对象 下划线格式转为小驼峰格式
function objHumpTurn(data) {
if (typeof data != 'object' || !data) return data
if (Array.isArray(data)) {
return data.map(item => objHumpTurn(item))
}
const newData = {
}
for (let key in data) {
let newKey = key.replace(/_([a-z])/g, (p, m) => m.toUpperCase())
newData[newKey] = objHumpTurn(data[key])
}
return newData
}
let dataList = [
{
user_id: 1,
dept_id: 103,
user_name: 'admin',
nick_name: '张',
user_type: '00'
}, {
user_id: 2,
dept_id: 105,
user_name: 'test',
nick_name: '王',
user_type: '00'
}
]
console.log(objHumpTurn(dataList), '对象 下划线格式转为小驼峰格式');
对象 小驼峰格式转为下划线格式
function objConnectorTurn(data) {
if (typeof data != 'object' || !data) return data
if (Array.isArray(data)) {
return data.map(item => objConnectorTurn(item))
}
const newData = {
}
for (let key in data) {
let newKey = key.replace(/([A-Z])/g, (p, m) => `_${
m.toLowerCase()}`)
newData[newKey] = objConnectorTurn(data[key])
}
return newData
}
let dataStr = [
{
userId: 1,
deptId: 103,
userName: 'admin',
nickName: '张',
userType: '00'
},
{
userId: 2,
deptId: 105,
userName: 'test',
nickName: '王',
userType: '00'
}
]
console.log(objConnectorTurn(dataStr), '对象 小驼峰格式转为下划线格式');
数据对象key 驼峰下划线互相转化
const formatHumpLineTransfer = (data, type = 'hump') => {
if (typeof data != 'object' || !data) return data
if (Array.isArray(data)) {
return data.map(item => formatHumpLineTransfer(item, type))
}
const newData = {
}
for (let key in data) {
let newKey = key.replace(/_([a-z])/g, (p, m) => m.toUpperCase())
if (type === 'toLine') {
newKey = key.replace(/([A-Z])/g, (p, m) => `_${
m.toLowerCase()}`)
}
newData[newKey] = formatHumpLineTransfer(data[key], type)
}
return newData
}
console.log(formatHumpLineTransfer(dataList, 'hump'), '对象 下划线格式转为小驼峰格式');
console.log(formatHumpLineTransfer(dataStr, 'toLine'), '对象 小驼峰格式转为下划线格式');
结果