没啥难度,考察对api的熟练程度和一点递归思想(有点类似深拷贝),直接看代码吧:
let snakeToCamel = (str) => {
let parts = str.split("_");
let camelParts = parts.map((item, index) => {
if (index === 0) return item;
else return item[0].toUpperCase() + item.slice(1);
});
return camelParts.join("");
};
let convert = (obj) => {
if (typeof obj !== "object" || obj === null) return obj;
let newObj = {};
for (let key of Object.keys(obj)) {
let newKey = snakeToCamel(key);
newObj[newKey] = convert(obj[key]);
}
return newObj;
};
测试:
const inputObj = {
first_name: "John",
last_name: "Doe",
address_info: {
street_name: "123 Main St",
city_name: "Example City",
},
};
const outputObj = convert(inputObj);
console.log(outputObj);
// 结果
{
firstName: 'John',
lastName: 'Doe',
addressInfo: { streetName: '123 Main St', cityName: 'Example City' }
}