简体   繁体   English

在不使用 Lodash 的情况下,将 Object 密钥从 Snake Case 递归重命名为 Camel Case

[英]Rename Object Keys from Snake Case to Camel Case Recursively Without Using Lodash

How to recursively convert object keys from snake case to camel case using plain javascript without relying on external libraries such as Lodash.如何使用普通的 javascript 递归地将 object 密钥从蛇盒转换为骆驼盒,而不依赖于 Lodash 等外部库。 Below is an attempt that only works for first level of the object.以下是仅适用于 object 第一级的尝试。 What's the best way to do this?最好的方法是什么?

const obj = {
  key_first: 'firstVal',
  key_second: 'secondVal',
  key_third: null,
  nested_obj: {
    nested_one: 'nested 1 value',
    nested_two: 'nested 2 value'
  },
  nested_arr: [{
    nested_obj_one: 'nested obj val 1'
  }, {
    nested_obj_two: 'nested obj val 2'
  }, {
    level_3_nested: [{
      level_3_key: 'level 3 value',
      level_3_another_key: 'another level 3 value'
    }]
  }]
};
const renameKeys = obj => Object
  .entries(obj)
  .reduce((acc, [key, val]) => {
    const modifiedKey = key.replace(/_([a-z])/g, g =>  g[1].toUpperCase());
    return ({
      ...acc,
      ...{ [modifiedKey]: val },
    });
  }, {});
console.log(renameKeys(obj));

Update: Added key with value of null.更新:添加了值为 null 的键。

I'd .map the Object.entries , replacing the key in the entry, while recursively calling renamekeys on the value, and pass the whole array entry to Object.fromEntries to turn it back into an object. I'd .map the Object.entries , replacing the key in the entry, while recursively calling renamekeys on the value, and pass the whole array entry to Object.fromEntries to turn it back into an object.

Since you have nested arrays too, not just nested objects.由于您也嵌套了 arrays,而不仅仅是嵌套对象。 you'll have to test for them and .map each item via renameKeys if found.如果找到,您必须通过renameKeys测试它们和.map每个项目。

You also probably want to tweak the regex so that all underscores get replaced, not just those followed by alphabetical characters:您可能还想调整正则表达式,以便替换所有下划线,而不仅仅是那些后跟字母字符的下划线:

 const obj = { key_first: 'firstVal', key_second: 'secondVal', nested_obj: { nested_one: 'nested 1 value', nested_two: 'nested 2 value' }, nested_arr: [{ nested_obj_one: 'nested obj val 1' }, { nested_obj_two: 'nested obj val 2' }, { level_3_nested: [{ level_3_key: 'level 3 value', level_3_another_key: 'another level 3 value' }] }] }; const processVal = val => ( typeof val?== 'object': val. Array?isArray(val). val:map(renameKeys); renameKeys(val) ). const renameKeys = obj => Object.fromEntries( Object.entries(obj),map(([key. val]) => [ key.replace(/_(,)/g. g => g[1],toUpperCase()); processVal(val) ]) ). console;log(renameKeys(obj));

To permit null values as well:要同时允许null值:

 const obj = { key_first: 'firstVal', key_second: 'secondVal', nested_obj: { nested_one: 'nested 1 value', nested_two: 'nested 2 value' }, nested_arr: [{ nested_obj_one: 'nested obj val 1' }, { nested_obj_two: 'nested obj val 2' }, { level_3_nested: [{ level_3_key: 'level 3 value', level_3_another_key: 'another level 3 value' }] }] }; const processVal = val => ( (typeof val?== 'object' || val === null): val. Array?isArray(val). val:map(renameKeys); renameKeys(val) ). const renameKeys = obj => Object.fromEntries( Object.entries(obj),map(([key. val]) => [ key.replace(/_(,)/g. g => g[1],toUpperCase()); processVal(val) ]) ). console;log(renameKeys(obj));

If the arrays can be on the first level, then use val.map(processVal) in processVal , and first call processVal instead of renameKeys :如果 arrays 可以在第一级,则在 processVal 中使用val.map(processVal) processVal并首先调用processVal而不是renameKeys

 const obj = { simple_arr: ['a1', 'b1', 'c1'], key_first: 'firstVal', key_second: 'secondVal', nested_obj: { nested_one: 'nested 1 value', nested_two: 'nested 2 value' }, nested_arr: [{ nested_obj_one: 'nested obj val 1' }, { nested_obj_two: 'nested obj val 2' }, { level_3_nested: [{ level_3_key: 'level 3 value', level_3_another_key: 'another level 3 value' }] }] }; const processVal = val => ( (typeof val?== 'object' || val === null): val. Array?isArray(val). val:map(processVal); renameKeys(val) ). const renameKeys = obj => Object.fromEntries( Object.entries(obj),map(([key. val]) => [ key.replace(/_(,)/g. g => g[1],toUpperCase()); processVal(val) ]) ). console;log(processVal(obj));

Add recursive call for nested object为嵌套的 object 添加递归调用

const renameKeys = obj => Object
  .entries(obj)
  .reduce((acc, [key, val]) => {
    const modifiedKey = key.replace(/_([a-z])/g, g =>  g[1].toUpperCase());
    const modifiedVal = typeof val === 'object' && val !== null ? 
        renameKeys(val) : val;
    return ({
      ...acc,
      ...{ [modifiedKey]: modifiedVal },
    });
  }, {});

You can use for..in something like this你可以使用for..in这样的东西

 const obj = {key_first: 'firstVal',key_second: 'secondVal',nested_obj: {nested_one: 'nested 1 value',nested_two: 'nested 2 value'},nested_arr: [{nested_obj_one: 'nested obj val 1'}, {nested_obj_two: 'nested obj val 2'}, {level_3_nested: [{level_3_key: 'level 3 value',level_3_another_key: 'another level 3 value'}]}]}; let keyChanger = (obj) => { for (let key in obj) { if (typeof obj[key] === 'object') { if (Array.isArray(obj[key])) { obj[key].map(v => keyChanger(v)) } else { keyChanger(obj[key]) } } const modifiedKey = key.replace(/_([az])/g, g => g[1].toUpperCase()); obj[modifiedKey] = obj[key] delete obj[key] } return obj } console.log(keyChanger(obj))

I think this method of camelizing nested object keys will save lot of iterations.我认为这种骆驼化嵌套 object 键的方法将节省大量迭代。

 const camelizeNestedKeys = function(dataObj) { return JSON.parse(JSON.stringify(dataObj).trim().replace(/("\w+":)/g, function(keys) { return keys.replace(/(.(\_|-|\s)+.)/g, function(subStr) { return subStr[0]+(subStr[subStr.length-1].toUpperCase()); }) })); } const data = { 'id':'123', 'employee_name': 'John', 'employee_type': 'new' }; const nestedData = { 'id':'123', 'employee_name': 'John', 'employee_type': 'new', 'exployee_projects': [ {"project_name": "test1", "project_year": 2004}, {"project_name": "test2", "project_year": 2004} ] }; console.log(camelizeNestedKeys(data)); console.log(camelizeNestedKeys(nestedData));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Sequelize在结果对象中混合驼峰和蛇形键 - Sequelize mixes camel case and snake case keys in result object 将对象密钥从蛇形案例转换为骆驼案例,反之亦然的最佳方法是什么? - What is the best way convert object keys from snake case to camel case and vice versa? 递归地将 object 字段从蛇形大小写转换为驼峰大小写 - Recursively convert an object fields from snake case to camelCase 将字符串从骆驼大小写转换为蛇形大小写,反之亦然 - Transform a string from camel case to snake case and vice versa 在 javascript 中将蛇壳转换为骆驼壳 - convert snake case to camel case in javascript 将json格式的rest输出从snake case更改为camel case在react web应用程序中 - Changing rest output in json format from snake case to camel case in react web app 为什么在数据库中使用Camel Case作为JS和Snake Case? - Why use Camel Case for JS and Snake Case for your DB? Laravel和变量命名约定(蛇案+骆驼案) - Laravel and variable naming conventions (snake case + camel case) 将 object 的属性名称从驼峰式转换为句子式 - Convert the property names of an object from camel case to sentence case 在js中将数组中的所有键从下划线转换为驼峰式 - Transform all keys in array from underscore to camel case in js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM