regex 将javascript对象的camelCase键转换为下划线_case

dsf9zpds  于 2022-11-18  发布在  Java
关注(0)|答案(9)|浏览(171)

我希望能够通过一个方法传递任何包含camelCase键的javascript对象,并返回一个带有underline_case键的对象,Map到相同的值。
所以,我有这个:

var camelCased = {firstName: 'Jon', lastName: 'Smith'}

我需要一个方法来输出这个:

{first_name: 'Jon', last_name: 'Jon'}

如果要编写一个方法,使其接受具有任意数量的键/值对的任何对象,并输出该对象的下划线大小写版本,最快的方法是什么?

qmelpv7a

qmelpv7a1#

下面是将camelCase转换为带下划线文本的函数(请参见jsfiddle):

function camelToUnderscore(key) {
    return key.replace( /([A-Z])/g, "_$1").toLowerCase();
}

console.log(camelToUnderscore('helloWorldWhatsUp'));

然后你可以直接循环(参见other jsfiddle):

var original = {
    whatsUp: 'you',
    myName: 'is Bob'
},
    newObject = {};

function camelToUnderscore(key) {
    return key.replace( /([A-Z])/g, "_$1" ).toLowerCase();
}

for(var camel in original) {
    newObject[camelToUnderscore(camel)] = original[camel];
}

console.log(newObject);
l7wslrjt

l7wslrjt2#

如果您的对象具有子对象,则可以使用递归并变更所有属性:

function camelCaseKeysToUnderscore(obj){
    if (typeof(obj) != "object") return obj;

    for(var oldName in obj){

        // Camel to underscore
        newName = oldName.replace(/([A-Z])/g, function($1){return "_"+$1.toLowerCase();});

        // Only process if names are different
        if (newName != oldName) {
            // Check for the old property name to avoid a ReferenceError in strict mode.
            if (obj.hasOwnProperty(oldName)) {
                obj[newName] = obj[oldName];
                delete obj[oldName];
            }
        }

        // Recursion
        if (typeof(obj[newName]) == "object") {
            obj[newName] = camelCaseKeysToUnderscore(obj[newName]);
        }

    }
    return obj;
}

因此,对于这样一个对象:

var obj = {
    userId: 20,
    userName: "John",
    subItem: {
        paramOne: "test",
        paramTwo: false
    }
}

newobj = camelCaseKeysToUnderscore(obj);

您将获得:

{
    user_id: 20,
    user_name: "John",
    sub_item: {
        param_one: "test",
        param_two: false
    }
}
w3nuxt5m

w3nuxt5m3#

es6节点解决方案如下。要使用,需要此文件,然后将您要转换的对象传递到函数中,它将返回对象的camelcased / snakecased副本。

const snakecase = require('lodash.snakecase');

const traverseObj = (obj) => {
  const traverseArr = (arr) => {
    arr.forEach((v) => {
      if (v) {
        if (v.constructor === Object) {
          traverseObj(v);
        } else if (v.constructor === Array) {
          traverseArr(v);
        }
      }
    });
  };

  Object.keys(obj).forEach((k) => {
    if (obj[k]) {
      if (obj[k].constructor === Object) {
        traverseObj(obj[k]);
      } else if (obj[k].constructor === Array) {
        traverseArr(obj[k]);
      }
    }

    const sck = snakecase(k);
    if (sck !== k) {
      obj[sck] = obj[k];
      delete obj[k];
    }
  });
};

module.exports = (o) => {
  if (!o || o.constructor !== Object) return o;

  const obj = Object.assign({}, o);

  traverseObj(obj);

  return obj;
};
pdsfdshx

pdsfdshx4#

在JS和python/ruby对象之间工作时遇到了这个问题。我注意到公认的解决方案是使用for in,这将向您抛出eslint错误消息,参考:https://github.com/airbnb/javascript/issues/851,其中提到第11.1条规则,内容是:使用纯功能而非副作用参考:https://github.com/airbnb/javascript#iterators--nope
为此,我想我会分享下面通过了上述规则。

import { snakeCase } from 'lodash'; // or use the regex in the accepted answer

camelCase = obj => {
  const camelCaseObj = {};
  for (const key of Object.keys(obj)){
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
     camelCaseObj[snakeCase(key)] = obj[key];
    }
  }

  return camelCaseObj;
};
vd8tlhqk

vd8tlhqk5#

Marcos Dimitrio在上面发布了他的转换函数,它可以工作,但不是一个纯函数,因为它改变了传入的原始对象,这可能是一个不希望的副作用。下面返回一个新对象,它不修改原始对象。

export function camelCaseKeysToSnake(obj){
  if (typeof(obj) != "object") return obj;
  let newObj = {...obj}
  for(var oldName in newObj){

      // Camel to underscore
      let newName = oldName.replace(/([A-Z])/g, function($1){return "_"+$1.toLowerCase();});

      // Only process if names are different
      if (newName != oldName) {
          // Check for the old property name to avoid a ReferenceError in strict mode.
          if (newObj.hasOwnProperty(oldName)) {
              newObj[newName] = newObj[oldName];
              delete newObj[oldName];
          }
      }

      // Recursion
      if (typeof(newObj[newName]) == "object") {
          newObj[newName] = camelCaseKeysToSnake(newObj[newName]);
      }
  }
  return newObj;
}
rqcrx0a6

rqcrx0a66#

此库的作用是:case-converter它将snake_case转换为camelCase,反之亦然

const caseConverter = require('case-converter')

  const snakeCase = {
    an_object: {
      nested_string: 'nested content',
      nested_array: [{ an_object: 'something' }]
    },
    an_array: [
      { zero_index: 0 },
      { one_index: 1 }
    ]
  }

  const camelCase = caseConverter.toCamelCase(snakeCase);

  console.log(camelCase)
  /*
    {
      anObject: {
        nestedString: 'nested content',
        nestedArray: [{ anObject: 'something' }]
      },
      anArray: [
        { zeroIndex: 0 },
        { oneIndex: 1 }
      ]
    }
  */
hsvhsicv

hsvhsicv7#

根据上面建议,不推荐使用case-converter库,请使用snakecase-keys代替-https://github.com/bendrucker/snakecase-keys
还支持嵌套对象和排除。

s1ag04yj

s1ag04yj8#

以上任何一个snakeCase函数都可以在reduce函数中使用:

const snakeCase = [lodash / case-converter / homebrew]

const snakeCasedObject = Object.keys(obj).reduce((result, key) => ({
      ...result,
      [snakeCase(key)]: obj[key],
    }), {})
mnowg1ta

mnowg1ta9#

jsfiddle(第一个字母)

//This function will rename one property to another in place
Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName == newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};

//rename this to something like camelCase to snakeCase
function doStuff(object) {
    for (var property in object) {
        if (object.hasOwnProperty(property)) {
            var r = property.replace(/([A-Z])/, function(v) { return '_' + v.toLowerCase(); });
            console.log(object);
            object.renameProperty(property, r);
            console.log(object);
        }
    }
}

//example object
var camelCased = {firstName: 'Jon', lastName: 'Smith'};
doStuff(camelCased);

***注意:****请记住删除所有console.log,因为生产代码不需要它们 *

相关问题