Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert returned JSON Object Properties to (lower first) camelCase

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?

like image 721
Jon Wells Avatar asked Oct 17 '12 10:10

Jon Wells


5 Answers

If you would use lodash instead of underscore, this would do:

_.mapKeys(obj, (v, k) => _.camelCase(k))

This would convert both TitleCase and snake_case to camelCase. Note that it is not recursive though.

like image 146
mik01aj Avatar answered Nov 05 '22 07:11

mik01aj


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
    }
}
like image 28
brandonscript Avatar answered Nov 05 '22 09:11

brandonscript


You can do this with this recursive function (with lodash and ES6):

import { camelCase } from 'lodash';

const camelizeKeys = (obj) => {
  if (Array.isArray(obj)) {
    return obj.map(v => camelizeKeys(v));
  } else if (obj != null && obj.constructor === Object) {
    return Object.keys(obj).reduce(
      (result, key) => ({
        ...result,
        [camelCase(key)]: camelizeKeys(obj[key]),
      }),
      {},
    );
  }
  return obj;
};

Test:

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

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

Output:

{  
   "firstName": "John",
   "lastName": "Smith",
   "birthDate": "2018-05-31T09:03:57.844Z",
   "arrayTest":[  
      "one",
      "TWO",
      3
   ],
   "thisKey":{  
      "thisSubKey": 42
   }
}
like image 56
jeshio Avatar answered Nov 05 '22 09:11

jeshio


To change a plain object's keys from snake_case to camelCase recursively try the following
(which uses Lodash):

function objectKeysToCamelCase(snake_case_object) {
  var camelCaseObject = {};
  _.forEach(
    snake_case_object,
    function(value, key) {
      if (_.isPlainObject(value) || _.isArray(value)) {     // checks that a value is a plain object or an array - for recursive key conversion
        value = objectKeysToCamelCase(value);               // recursively update keys of any values that are also objects
      }
      camelCaseObject[_.camelCase(key)] = value;
    }
  )
  return camelCaseObject;
};

test in this PLUNKER

Note: also works recursively for objects within arrays

like image 24
goredwards Avatar answered Nov 05 '22 09:11

goredwards


Using lodash and ES6, this will replace all keys recursively to camelcase:

const camelCaseKeys = (obj) => {
  if (!_.isObject(obj)) {
    return obj;
  } else if (_.isArray(obj)) {
    return obj.map((v) => camelCaseKeys(v));
  }
  return _.reduce(obj, (r, v, k) => {
    return { 
      ...r, 
      [_.camelCase(k)]: camelCaseKeys(v) 
    };
  }, {});
};      
like image 14
guatedude2 Avatar answered Nov 05 '22 09:11

guatedude2