Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert snake case to camelcase in my app

Tags:

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!

like image 877
Jwqq Avatar asked Nov 20 '16 23:11

Jwqq


People also ask

Is snake case or camelCase better?

Screaming snake case is used for variables. Scripting languages, as demonstrated in the Python style guide, recommend snake case in the instances where C-based languages use camel case.


1 Answers

Use _.mapKeys() instead of _.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>

If you need to ignore the redundant value param, you can use _.rearg() on _.camelCase() to generate a function that takes the 2nd param (the key) instead of the 1st param (the 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>
like image 54
Ori Drori Avatar answered Oct 11 '22 06:10

Ori Drori