我有从API返回的JSON,如下所示:
Contacts: [{ GivenName: "Matt", FamilyName:"Berry" }]
为了使其与我的代码风格(camelCase-小写首字母)保持一致,我想对数组进行转换以产生以下内容:
contacts: [{ givenName: "Matt", familyName:"Berry" }]
最简单/最好的方法是什么?创建一个新的Contact对象并遍历返回数组中的所有联系人?
var jsonContacts = json["Contacts"], contacts= []; _.each(jsonContacts , function(item){ var contact = new Contact( item.GivenName, item.FamilyName ); contacts.push(contact); });
还是可以映射原图或以某种方式对其进行转换?
这是一个可靠的递归函数,它将适当地驼峰化所有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 } }