我的寄宿密码里有个很奇怪的问题
我有像这样的东西
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'
}这太奇怪了,我不知道哪里出了问题。有人能帮我一下吗?非常感谢!
发布于 2016-11-21 07:30:23
使用_.mapKeys()而不是_.mapValues()
var data = {
'id': '123',
'employee_name': 'John',
'employee_type': 'new'
};
var newObj = _.mapKeys(data, (value, key) => _.camelCase(key));
console.log('newObj: ', newObj);<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
如果需要忽略冗余的value参数,可以在_.camelCase()上使用_.rearg()生成一个函数,该函数接受第二个参数( key)而不是第一个参数( value)。
var data = {
'id': '123',
'employee_name': 'John',
'employee_type': 'new'
};
var newObj = _.mapKeys(data, _.rearg(_.camelCase, 1));
console.log('newObj: ', newObj);<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
发布于 2020-04-23 05:09:45
仅对于字符串(ES6+),将snake-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发布于 2016-11-21 07:34:32
您还可以轻松地为此创建自己的函数:
function camelCase(obj) {
var newObj = {};
for (d in obj) {
if (obj.hasOwnProperty(d)) {
newObj[d.replace(/(\_\w)/g, function(k) {
return k[1].toUpperCase();
})] = obj[d];
}
}
return newObj;
}
var data = {
'id': '123',
'employee_name': 'John',
'employee_type': 'new'
}
console.log(camelCase(data));
https://stackoverflow.com/questions/40710628
复制相似问题