How to convert snake case to camelcase in my app

蹲街弑〆低调 提交于 2021-02-18 20:30:08

问题


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!


回答1:


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>



回答2:


You can also easily create your own function for that:

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



回答3:


snake-case to camelCase only for string (ES6+):

const snakeToCamel = str =>
  str.toLowerCase().replace(/([-_][a-z])/g, group =>
    group
      .toUpperCase()
      .replace('-', '')
      .replace('_', '')
  );

result:

console.log(snakeToCamel('TO_CAMEL')) //toCamel
console.log(snakeToCamel('to_camel')) //toCamel
console.log(snakeToCamel('TO-CAMEL')) //toCamel
console.log(snakeToCamel('to-camel')) //toCamel



回答4:


Here is another answer using simple for loop.

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

var output = {}
for (var key in data) {
  output[_.camelCase(key)] = data[key];
}



回答5:


For my use case I needed (or wanted) a function that would handle any arbitrary json object, including nested objects, arrays, etc. Came up with this, seems to be working so far:

const fromSnakeToCamel = (data) => {
  if (_.isArray(data)) {
    return _.map(data, fromSnakeToCamel);
  }

  if (_.isObject(data)) {
    return _(data)
      .mapKeys((v, k) => _.camelCase(k))
      .mapValues((v, k) => fromSnakeToCamel(v))
      .value();
  }

  return data;
}

Note that if it's not an array or an object, I just return the data because I only actually want to convert keys. Anyway, hope this helps someone




回答6:


If you want to convert the nested object, then using lodash can be a bit painful.

I tried using regex, JSON.parse & JSON.stringify and here is the code for the same

below code returns the new object that is having camel case instead of snake case

//input
var data = {
   'id': '123',
   'employee_name': 'John',
   'employee_type': {'new_name': 'foo'}  
};

JSON.parse(JSON.stringify(data).replace(
                /(_\w)\w+":/g,
                match => match[1].toUpperCase() + match.substring(2)
              ));

{
   'id': '123',
   'employeeName': 'John',
   'employeeType': {'newName': 'foo'}  
}



回答7:


These are all good answers, but they did not fit what I needed. I like Ashish's answer because it handles nested objects, but what if there are underscores in the data that you want? So, here is a varient on Bambam's answer to make it recursive, because lodash can sometimes be a pain.

function toCamelCase (obj) {
    let rtn = obj
    if (typeof (obj) === 'object') {
        if (obj instanceof Array) {
            rtn = obj.map(toCamelCase)
        } else {
            rtn = {}
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                     const newKey = key.replace(/(_\w)/g, k => k[1].toUpperCase())
                     rtn[newKey] = toCamelCase(obj[key])
                }
            }
        }
    }
    return rtn
}



回答8:


Yeah, I'm not a big fan of libraries. Here's how to do it in native Javascript...

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

// #1 simple function which converts a string from snake case to camel case ...
const snakeToCamel = s => s.replace(/(_\w)/g, k => k[1].toUpperCase())

// #2 create new data object with camelCase keys...
data = Object.entries(data).reduce((x,[k,v]) => (x[snakeToCamel(k)]=v) && x, {})

console.log(data)



回答9:


another way

 _(data)
     .keys()
     .map(_.camelCase)
     .zipObject(_.values(data))
     .value()



回答10:


I really like Mardok's version with nested objects, only issue is that it converts "null" to {}

here mine:

import _ from 'lodash';

export const toCamelCase: any = (obj: any) => {
    let rtn = obj
    if (typeof obj === 'object') {
        if (obj instanceof Array) {
            rtn = obj.map(toCamelCase)
        }
        else if (_.isEmpty(obj)) {
            rtn = null
        } else {
            rtn = {}
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    const newKey = key.replace(/(_\w)/g, k => k[1].toUpperCase())
                    rtn[newKey] = toCamelCase(obj[key])
                }
            }
        }
    }
    return rtn
}



回答11:


Creates camelized object recursively.

function camelCase(obj) {
  const newObj = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
        const value = obj[key];
        const keyCamel = key.replace(/(\_\w)/g, (match) => match[1].toUpperCase());
        const isRecursive = typeof value === 'object';
        newObj[keyCamel] = isRecursive ? camelCase(value) : value;
    }
  }
  return newObj;
}

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

camelCase(data);


来源:https://stackoverflow.com/questions/40710628/how-to-convert-snake-case-to-camelcase-in-my-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!