JSON格式将key转换为驼峰---js解法

时间:2024-10-10 07:35:32
var obj = {"a_b": {"a_b_c": {"a_b_c_d": "a_b_c_d"}}} function toString(obj){ function Camel(str){ return str.toLowerCase().replace(/_(\w)/g,function(first,letter){ return letter.toUpperCase() }) } if(obj instanceof Array){ obj.forEach(function(v,index){ toString(v) }) } else if(obj instanceof Object){ Object.keys(obj).forEach(function(key){ var newKey = Camel(key) if(newKey!=key){ obj[newKey] = obj[key] delete(obj[key]) } toString(obj[newKey]) }) } return JSON.stringify(obj) } console.log(toString(obj))