手写下划线转驼峰命名要考虑对象的深度递归情况
看别人的面经发现一道题,一时手痒就写了下,不知道对错。
题源:https://www.nowcoder.com/discuss/470638184494276608
const underscoreToCamelCase = (data) => { if (Array.isArray(data)) { return data.map(underscoreToCamelCase); } else if (typeof data === "object" && data != null) { const res = {}; for (const key in data) { let newKey = ""; if (key.indexOf("_") != -1) { let upper = false; for (let i = 0; i < key.length; i++) { if (key.charAt(i) === "_") { upper = true; continue; } newKey += upper ? key.charAt(i).toUpperCase() : key.charAt(i); upper = false; } } res[newKey ? newKey : key] = underscoreToCamelCase(data[key]); } return res; } else { return data; } }; // 测试 const data = { first_name: "John", last_name: "Doe", age: 30, address: { city_name: "New York", country_code: "US", }, hobbies: ["reading_books", "playing_games"], }; console.table(underscoreToCamelCase(data));