后端数据返回的snake_case格式,但前端的规范为驼峰格式,实现一种snake_case转驼峰的方法
function snakeCaseToCamelCase(input){ let inputStr = JSON.stringify(input); var arr = new Array(inputStr.length); let isKey = false; let count = 0;// key value 必须配对 let skipCount = 0; for(var i=0,j=inputStr.length; i<j; i++){ if(!isKey){ arr.push(inputStr[i]); if(inputStr[i]===\'\\\'){ i++; arr.push(inputStr[i]); } else if(inputStr[i]===\'"\'){ if(skipCount){ skipCount--; } else{ count++; } isKey = count%2===1; } continue; } if(inputStr[i] === \'_\'){ i++; arr.push(inputStr[i].toUpperCase()); continue; } else if(inputStr[i]===\'\\\'){ arr.push(inputStr[i]); arr.push(inputStr[++i]); continue; } else if(inputStr[i]===\'"\'){ isKey = false; if(inputStr[i+2]===\'"\'){ skipCount = 2; } else{ skipCount = 0; } count++; } arr.push(inputStr[i]); } return JSON.parse(arr.join(\'\')); }
版权声明:本文为dzqdzq原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。