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" }]
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?
Well I took up the challenge and think I figured it out:
Property converter (jsfiddle)
The trick is handling the objects as arrays of object properties.
Took the challenge with lodash and some es6+ features Here is my implementation with the reduce function.
If you would use lodash instead of underscore, this would do:
This would convert both
TitleCase
andsnake_case
tocamelCase
. Note that it is not recursive though.I needed a generic method that accepted an array or object. This is what I'm using (I borrowed KyorCode's
firstToLower()
implementation):Example calls:
This is my take; more readable and with less nesting than brandoncode's implementation, and with more room for handling edge cases like
Date
(which isn't handled, by the way) ornull
:Thanks other I do this (recursive function with lodash and ES6):
Test:
Output: