我的 lodash 代码中有一个非常奇怪的问题
我有类似的东西
data = {
'id':'123',
'employee_name': 'John',
'employee_type': 'new'
}
var newObj = _.mapValues(data, function (value, key) {
var t = _.camelCase(key);
console.log(t) -> shows employeeName and employeeType
return _.camelCase(key);
});
我原以为我的 newObj 会变成
data = {
'id':'123',
'employeeName': 'John',
'employeeType': 'new'
}
在我运行上面的代码之后,它仍然保持原样
data = {
'id':'123',
'employee_name': 'John',
'employee_type': 'new'
}
这太奇怪了,我不确定哪里出了问题。有人可以帮我解决这个问题吗?非常感谢!
最佳答案
仅针对字符串 (ES6+) 将 snake_case 或 kebab-case 替换为 camelCase:
const snakeToCamel = str =>
str.toLowerCase().replace(/([-_][a-z])/g, group =>
group
.toUpperCase()
.replace('-', '')
.replace('_', '')
);
结果:
console.log(snakeToCamel('TO_CAMEL')) //toCamel
console.log(snakeToCamel('to_camel')) //toCamel
console.log(snakeToCamel('TO-CAMEL')) //toCamel
console.log(snakeToCamel('to-camel')) //toCamel
关于javascript - 如何在我的应用程序中将 snake case 转换为 camelcase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40710628/