这是一个可靠的递归函数,它将适当地驼峰化所有Javascript对象的属性:
function toCamel(o) { var newO, origKey, newKey, value if (o instanceof Array) { return o.map(function(value) { if (typeof value === "object") { value = toCamel(value) } return value }) } else { newO = {} for (origKey in o) { if (o.hasOwnProperty(origKey)) { newKey = (origKey.charAt(0).toLowerCase() + origKey.slice(1) || origKey).toString() value = o[origKey] if (value instanceof Array || (value !== null && value.constructor === Object)) { value = toCamel(value) } newO[newKey] = value } } } return newO}测试:
var obj = { 'FirstName': 'John', 'LastName': 'Smith', 'BirthDate': new Date(), 'ArrayTest': ['one', 'TWO', 3], 'ThisKey': { 'This-Sub-Key': 42 }}console.log(JSON.stringify(toCamel(obj)))输出:
{ "firstName":"John", "lastName":"Smith", "birthDate":"2017-02-13T19:02:09.708Z", "arrayTest": [ "one", "TWO", 3 ], "thisKey":{ "this-Sub-Key":42 }}


