用原生js 把一个json对象从下划线转换成小驼峰形式
时间: 2023-03-29 12:01:19 浏览: 103
可以使用以下代码将一个json对象从下划线转换成小驼峰形式:
```javascript
function toCamelCase(obj) {
if (typeof obj !== 'object') {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(toCamelCase);
}
const result = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const camelKey = key.replace(/_([a-z])/g, (match, p1) => p1.toUpperCase());
result[camelKey] = toCamelCase(obj[key]);
}
}
return result;
}
```
使用方法:
```javascript
const underscoreObj = {
first_name: 'John',
last_name: 'Doe',
address: {
street_name: 'Main St',
city_name: 'Anytown',
state_code: 'CA'
}
};
const camelObj = toCamelCase(underscoreObj);
console.log(camelObj);
```
输出结果:
```javascript
{
firstName: 'John',
lastName: 'Doe',
address: {
streetName: 'Main St',
cityName: 'Anytown',
stateCode: 'CA'
}
}
```
阅读全文