Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  46] [ 1]  / answers: 1 / hits: 116395  / 12 Years ago, wed, october 17, 2012, 12:00:00

I have JSON returned from an API like so:


Contacts: [{ GivenName: "Matt", FamilyName: "Berry" }]

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" }]

What's 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 array or transform it somehow?


More From » jquery

 Answers
8

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
}


Test:



var obj = {
'FirstName': 'John',
'LastName': 'Smith',
'BirthDate': new Date(),
'ArrayTest': ['one', 'TWO', 3],
'ThisKey': {
'This-Sub-Key': 42
}
}

console.log(JSON.stringify(toCamel(obj)))


Output:



{
firstName:John,
lastName:Smith,
birthDate:2017-02-13T19:02:09.708Z,
arrayTest: [
one,
TWO,
3
],
thisKey:{
this-Sub-Key:42
}
}

[#82506] Tuesday, October 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jazminuniquer

Total Points: 63
Total Questions: 121
Total Answers: 96

Location: Cambodia
Member since Thu, May 21, 2020
4 Years ago
;