将javascript对象camelCase键转换为underscore_case

时间:2015-06-21 23:21:13

标签: javascript regex

我希望能够通过方法传递包含camelCase键的任何javascript对象,并返回一个带有underscore_case键的对象,映射到相同的值。

所以,我有这个:

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

我想要一个方法输出:

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

编写方法的最快方法是什么,该方法接受具有任意数量的键/值对的任何对象,并输出该对象的下划线版本?

7 个答案:

答案 0 :(得分:4)

以下是将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);

答案 1 :(得分:2)

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

答案 2 :(得分:1)

如果您有一个带有子对象的对象,您可以使用递归并更改所有属性:

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

答案 3 :(得分:1)

下面的

es6节点解决方案。使用时,需要此文件,然后将要转换的对象传递到函数中,它将返回该对象的驼峰/蛇形副本。

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

答案 4 :(得分:1)

在JS和python / ruby​​对象之间工作时,请解决此确切的问题。我注意到已接受的解决方案正在使用for in,它将向您抛出eslint错误消息ref:decode a JSON string暗示了规则11.1 re:使用纯函数而不是副作用ref:https://github.com/airbnb/javascript/issues/851 < / p>

为此,我想分享以下通过了上述规则的内容。

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

答案 5 :(得分:0)

这个库正是这样做的: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 }
      ]
    }
  */

答案 6 :(得分:-1)

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,因为生产代码不需要 < / p>