我希望能够通过一个方法传递包含驼峰键的任何 javascript 对象,并返回一个带有 underscore_case 键的对象,映射到相同的值。
所以,我有这个:
var camelCased = {firstName: 'Jon', lastName: 'Smith'}
Run Code Online (Sandbox Code Playgroud)
我想要一种方法来输出这个:
{first_name: 'Jon', last_name: 'Jon'}
Run Code Online (Sandbox Code Playgroud)
编写一个方法,该方法接受具有任意数量键/值对的任何对象并输出该对象的 underscore_cased 版本的最快方法是什么?
这是将驼峰大小写转换为下划线文本的函数(请参阅jsfiddle):
function camelToUnderscore(key) {
return key.replace( /([A-Z])/g, "_$1").toLowerCase();
}
console.log(camelToUnderscore('helloWorldWhatsUp'));
Run Code Online (Sandbox Code Playgroud)
然后你可以循环(参见其他 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);
Run Code Online (Sandbox Code Playgroud)
如果您有一个带有子对象的对象,则可以使用递归并更改所有属性:
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;
}
Run Code Online (Sandbox Code Playgroud)
因此,对于这样的对象:
var obj = {
userId: 20,
userName: "John",
subItem: {
paramOne: "test",
paramTwo: false
}
}
newobj = camelCaseKeysToUnderscore(obj);
Run Code Online (Sandbox Code Playgroud)
你会得到:
{
user_id: 20,
user_name: "John",
sub_item: {
param_one: "test",
param_two: false
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13691 次 |
最近记录: |