JSON对象下划线转换驼峰 驼峰转下划线
时间: 2023-09-03 22:15:44 浏览: 54
JSON对象下划线转换驼峰:
下划线转驼峰的过程可以通过正则表达式和replace()方法实现。
例如,将下划线连接的JSON对象键名转换为驼峰式:
```javascript
let obj = {
first_name: 'John',
last_name: 'Doe',
email_address: 'johndoe@example.com'
};
let newObj = {};
for (let key in obj) {
let newKey = key.replace(/_([a-z])/g, function(match, letter) {
return letter.toUpperCase();
});
newObj[newKey] = obj[key];
}
console.log(newObj);
// {firstName: "John", lastName: "Doe", emailAddress: "johndoe@example.com"}
```
驼峰转下划线:
将驼峰式的JSON对象键名转换为下划线连接的形式,也可以通过正则表达式和replace()方法实现。
例如,将驼峰式的JSON对象键名转换为下划线连接的形式:
```javascript
let obj = {
firstName: 'John',
lastName: 'Doe',
emailAddress: 'johndoe@example.com'
};
let newObj = {};
for (let key in obj) {
let newKey = key.replace(/[A-Z]/g, function(match) {
return '_' + match.toLowerCase();
});
newObj[newKey] = obj[key];
}
console.log(newObj);
// {first_name: "John", last_name: "Doe", email_address: "johndoe@example.com"}
```