Today I saw in the following question a challenge:
I have JSON returned from an API like so:
1: Contacts: [{ GivenName: "Matt", FamilyName:"Berry" }]
To keep things consistent with my code style (camelCase – lower case first letter), I want to transform the array to product the following:
1: contacts: [{ givenName: "Matt", familyName:"Berry" }]
The catch is that the names of the properties should be converted to the camelcase code style. I pondered about this for a little while, when it kinda hit me in the face. Javascript objects can be handles as arrays.
This allowed me to produce the following script to fix this issue:
1: var firstToLower = function(str) {
2: return str.charAt(0).toLowerCase() + str.slice(1);
3: };
4:
5: var firstToUpper = function(str) {
6: return str.charAt(0).toUpperCase() + str.slice(1);
7: };
8:
9: var mapToJsObject = function(o) {
10: var r = {};
11: $.map(o, function(item, index) {
12: r[firstToLower(index)] = o[index];
13: });
14: return r;
15: };
16:
17: var mapFromJsObject = function(o) {
18: var r = {};
19: $.map(o, function(item, index) {
20: r[firstToUpper(index)] = o[index];
21: });
22: return r;
23: };
Usage:
1: // Map to
2: var contacts = [{
3: GivenName: "Matt",
4: FamilyName: "Berry"},
5: {
6: GivenName: "Josh",
7: FamilyName: "Berry"},
8: {
9: GivenName: "Thomas",
10: FamilyName: "Berry"}];
11:
12: var mappedContacts = [];
13:
14: $.map(contacts, function(item) {
15: var m = mapToJsObject(item);
16: mappedContacts.push(m);
17: });
18:
19: alert(mappedContacts[0].givenName);
20:
21:
22: // Map from
23: var unmappedContacts = [];
24:
25: $.map(mappedContacts, function(item) {
26: var m = mapFromJsObject(item);
27: unmappedContacts.push(m);
28: });
29:
30: alert(unmappedContacts[0].GivenName);
Kinda cool I thought, so I decided to share this with you!
Until next time!
PS: I’ll start posting more now. I promise!