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?
Advertisement
Answer
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 } }