本文介绍了将返回的JSON对象属性转换为(最低优先级)camelCase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有从API返回的JSON,如下所示:
I have JSON returned from an API like so:
Contacts: [{ GivenName: "Matt", FamilyName:"Berry" }]
为使其与我的代码风格(camelCase-小写首字母)保持一致,我想对数组进行转换以产生以下内容:
To keep this consistent with my code style (camelCase - lower case first letter) I want to transform the array to produce the following:
contacts: [{ givenName: "Matt", familyName:"Berry" }]
最简单/最好的方法是什么?创建一个新的Contact对象并遍历返回数组中的所有联系人?
Whats the easiest/best way to do this? create a new Contact object and iterate over all the contacts in the returned array?
var jsonContacts = json["Contacts"],
contacts= [];
_.each(jsonContacts , function(item){
var contact = new Contact( item.GivenName, item.FamilyName );
contacts.push(contact);
});
还是可以映射原图或以某种方式对其进行转换?
or can I map the original or transform it somehow?
推荐答案
这是一个可靠的递归函数,可以正确驼峰化所有JavaScript对象的属性:
Here's a reliable, recursive function that will properly camelCase all of a JavaScript object's properties:
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
}
}
这篇关于将返回的JSON对象属性转换为(最低优先级)camelCase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!