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?
Using lodash, you can do it like this:
To change a plain object's keys from
snake_case
tocamelCase
recursively try the following(which uses Lodash):
test in this PLUNKER
Note: also works recursively for objects within arrays
Using lodash and ES6, this will replace all keys recursively to camelcase:
Shorthand:
Expanded:
This is a great use case for axios interceptors
Basically, define a client class and attach a before/after interceptor that converts the request/response data.
Here's a gist with a longer example using React/axios.
This solution based on the plain js solution above, uses loadash and Keeps an array if passed as a parameter and Only change the Keys
Updated code using the reference from https://plnkr.co/edit/jtsRo9yU12geH7fkQ0WL?p=preview This handles the Objects with array with objects inside it too and so on, by keeping arrays as arrays (which you can iterate over using map)