Jwqq Jwqq - 11 days ago 6
Javascript Question

How to convert snake case to camelcase in my app

I have a very weird issue in my lodash codes

I have something like

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);
});


I was expecting my newObj will become

data = {
'id':'123',
'employeeName': 'John',
'employeeType': 'new'
}


after I ran the codes above, it still stays the same as it was like

data = {
'id':'123',
'employee_name': 'John',
'employee_type': 'new'
}


This is super weird and I'm not sure what went wrong. Can someone help me about this? Thanks a lot!

Answer

Use _.mapKeys() instead of _.mapValues():

var data = {
   'id': '123',
   'employee_name': 'John',
   'employee_type': 'new'  
};

var newObj = _.mapKeys(data, function (value, key) {
     return _.camelCase(key);
});

console.log('newObj: ', newObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

You can use _.transform() instead of _.mapKeys() to get the same effect:

var data = {
  'id': '123',
  'employee_name': 'John',
  'employee_type': 'new'
};

var newObj = _.transform(data, function(result, value, key) {
  result[_.camelCase(key)] = value;
}, {});

console.log(newObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Comments