101

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?

kahlan88
  • 101
  • 1
  • 8
Jon Wells
  • 4,191
  • 9
  • 40
  • 69
  • 1
    If you are really burned to use the camelcase notation in your javascript you are going to have to map the incoming objects. http://api.jquery.com/jQuery.map/ should help you with with mapping. – KyorCode Oct 17 '12 at 10:07

26 Answers26

127

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.

mik01aj
  • 11,928
  • 15
  • 76
  • 119
105

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
    }
}
brandonscript
  • 68,675
  • 32
  • 163
  • 220
  • 1
    I would suggest checking for `o.hasOwnProperty(key)` and changing `if (typeof value === "object")` to `if (value !== null && typeof value === "object")`. Without the check for `value !== null` this function converts nulls to empty objects. – user619656 Jul 29 '15 at 07:50
  • Good tips - will add those in. – brandonscript Jul 29 '15 at 20:15
  • 2
    This will loose value information if o is Date object (or any Object which does not have own property). Checkout demo http://codepen.io/anon/pen/EPqZLY?editors=1010 – tsobe Feb 23 '16 at 15:00
  • A year later, I finally took the time to properly detect non-plain-object properties (like `Date`). We check that the constructor is an `Object` before camel-casing the rest of it. – brandonscript Feb 13 '17 at 19:03
  • @brandonscript, can you help me with this: http://stackoverflow.com/questions/42425537/lowercase-json-keys-to-camelcase ? – Marckaraujo Feb 23 '17 at 20:27
  • Woa, why did it camel-case the value for 'thisKey' as well... ? Surely the OP, or anybody, would not want the data changed as well. Just the property names? – PandaWood Mar 01 '17 at 01:05
  • What are you talking about? Please provide an example. Here is what I think you mean: https://jsfiddle.net/41zeshe2/. – brandonscript Mar 01 '17 at 01:11
  • @brandonscript You also need to check if the value of the property on the object is an array, and call it recursively then, too. – Colin DeClue Jun 02 '17 at 14:11
  • Yep, it does that. First if statement. – brandonscript Jun 02 '17 at 14:12
  • 3
    @brandonscript It actually misses if any properties are an array, yours only checks if the main object is an array. This line is missing a check to see if it's an array: `if (value !== null && value.constructor === Object)` Here's an example of yours failing: https://plnkr.co/edit/tEBYU3pQmJJZyl84CFo5 With the fix of checking for an array: https://plnkr.co/edit/78gDwcLChAOT31XGoLG6 – Justin Sep 20 '17 at 16:52
  • Good catch @Justin. Want to edit the answer? I’ll approve. – brandonscript Sep 20 '17 at 16:53
  • There is missing ` if (!isNaN(parseInt(origKey))) {` in array for - in other case it will also take 'extension methods' from TypeScript @brandonscript – Pixello Feb 08 '18 at 10:21
  • Not sure what you’re trying to suggest. Why would you want to search for a string key converted to an int? – brandonscript Feb 08 '18 at 15:37
  • No, i dont want to - just `if (o instanceof Array) { newO = [] for (origKey in o) {` is returning too much results - which are functions. – Pixello Feb 08 '18 at 19:42
  • Can you provide an example in a jsfiddle? I'll update the answer. – brandonscript Feb 08 '18 at 19:43
  • Sure, https://jsfiddle.net/9bdnc4fv/1/ look at that null `{"firstName":"John","lastName":"Smith","birthDate":"2018-02-08T20:01:58.044Z","arrayTest":["one","TWO",3,null],"thisKey":{"this-Sub-Key":42}}` @edit - updated with ToCamelCase – Pixello Feb 08 '18 at 20:02
  • OHH now I see what you're saying. I shouldn't have used `for (key in arr)` to iterate an array in the first place. Switching it to `forEach()` prevents this from happening. Or, even `.map()` will make it shorter. – brandonscript Feb 08 '18 at 20:44
  • I'd rather use the regex `/([A-Z]+)(.*)/` instead of blindly replacing the first char, it will also match something like DOB or URL (which would result in dOB with this solution) – Mordechai Jun 01 '20 at 19:57
  • @Mordechai regex parsing an object can be very dangerous. Use at your own risk. – brandonscript Jun 01 '20 at 20:59
58

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
   }
}
Robin Wieruch
  • 14,900
  • 10
  • 82
  • 107
jeshio
  • 605
  • 5
  • 7
25

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

Community
  • 1
  • 1
goredwards
  • 2,486
  • 2
  • 30
  • 40
  • Note that this doesn't work for well-known JSON objects which could contain objects or arrays. – Kody Apr 13 '17 at 18:46
  • @Kody by "well-known JSON objects" do you mean something like `{ "name_of": {"name_of_of":"John"}, "age_of":[{"array_object":"John"},40,50], "car_type":null }` as [defined here](https://www.w3schools.com/js/js_json_objects.asp) - it works fine for JSON objects & nested JSON objects - PLUNKER updated - but not for converting keys of objects (JSON or otherwise) inside arrays - due to the `_.isPlainObject(value)` check. – goredwards Apr 13 '17 at 23:11
  • 1
    @Kody - code & plunker updated just for you - now works with objects (JSON or otherwise) nested inside arrays :-) – goredwards Apr 13 '17 at 23:24
  • 1
    plunker really saved my lot of time. – khichar.anil May 25 '17 at 19:32
  • 1
    I changed _.isPlainObject(value) to _.isObject(value) and it worked for me, thanks! –  May 26 '17 at 01:13
  • took the liberty of publishing this to npm as a https://www.npmjs.com/package/camel-case-props – Capaj Aug 14 '17 at 14:52
  • 6
    Notice That This flattens an array if you pass to it - and returns an object instead – Gal Bracha Sep 03 '17 at 11:03
  • 3
    As @GalBracha said, this doesn't appear to keep arrays as arrays. I hacked this together instead: https://plnkr.co/edit/OnLVNqq7dHW1T3ukuyd1 – ropeladder Mar 12 '18 at 17:42
  • @ropeladder (and GalBracha) - well sleuthed - but note that the question specifically asks to convert JSON object properties - not array values - hence the solution is to accept / convert / return an object. – goredwards Mar 14 '18 at 21:37
16

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) 
    };
  }, {});
};      
guatedude2
  • 218
  • 3
  • 5
  • 1
    my favorite solution – garrettmac Jul 18 '18 at 19:07
  • 3
    This will fail if we have objects like this: [{ hello: 0 }, { hello: null }, { hello: undefined }, { hello: false }] it will return [{hello: {}}, {hello: {}}, {hello: {}), {hello: {}}] Can be fixed by adding if (obj === 0 || obj === null || obj === undefined || obj === false) { return obj; } – mikkeljuhl Aug 22 '18 at 09:15
  • Good catch the shorthand version was inconsistent with the expanded version. I've updated to show only expanded answer – guatedude2 Jan 27 '21 at 04:39
10

Just use humps

humps.camelize('hello_world');
humps.camelizeKeys(object, options); // will work through entire object

https://www.npmjs.com/package/humps

serraosays
  • 7,163
  • 3
  • 35
  • 60
Daniel Bernal
  • 334
  • 3
  • 7
6

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.

export default class Client {
    get(url, data, successCB, catchCB) {
        return this._perform('get', url, data, successCB, catchCB);
    }

    post(url, data, successCB, catchCB) {
        return this._perform('post', url, data, successCB, catchCB);
    }

    _perform(method, url, data, successCB, catchCB) {
        // https://github.com/axios/axios#interceptors
        // Add a response interceptor
        axios.interceptors.response.use((response) => {
            response.data = toCamelCase(response.data);
            return response;
        }, (error) => {
            error.data = toCamelCase(error.data);
            return Promise.reject(error);
        });

        // Add a request interceptor
        axios.interceptors.request.use((config) => {
            config.data = toSnakeCase(config.data);
            return config;
        }, (error) => {
            return Promise.reject(error);
        });

        return axios({
            method: method,
            url: API_URL + url,
            data: data,
            headers: {
                'Content-Type': 'application/json',
            },
        }).then(successCB).catch(catchCB)
    }
}

Here's a gist with a longer example using React/axios.

daino3
  • 4,386
  • 37
  • 48
  • 1
    IMO - this may be the best answer, using an interceptor is a very clean way to move all snake_case keys into camelCase and keep the code in a single sane place, tyvm – DrCord Feb 02 '21 at 21:03
5

there's a nice npm module for this.. https://www.npmjs.com/package/camelcase-keys

npm install camelcase-keys
const camelcaseKeys = require( "camelcase-keys" );

camelcaseKeys( { Contacts: [ { GivenName: "Matt", FamilyName: "Berry" } ] }, { deep: true } );

will return...

{ contacts: [ { givenName: "Matt", familyName: "Berry" } ] }
shunryu111
  • 5,895
  • 4
  • 27
  • 16
4

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

function camelCaseObject(o) {
    let newO, origKey, value
    if (o instanceof Array) {
        newO = []
        for (origKey in o) {
            value = o[origKey]
            if (typeof value === 'object') {
                value = camelCaseObject(value)
            }
            newO.push(value)
        }
    } else {
        newO = {}
        for (origKey in o) {
            if (o.hasOwnProperty(origKey)) {
                newO[_.camelCase(origKey)] = o[origKey]
            }
        }
    }
    return newO
}

// Example
const obj = [
{'my_key': 'value'},
 {'Another_Key':'anotherValue'},
 {'array_key':
   [{'me_too':2}]
  }
]
console.log(camelCaseObject(obj))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Gal Bracha
  • 19,004
  • 11
  • 72
  • 86
  • 1
    The function is only recursive in dealing with Arrays. Once it hits a non-Array object, it only camel-cases the top level of property keys. – Zarepheth May 09 '19 at 19:32
  • 1
    This is not pure JS solution. This requires lodash so technically it's not pure JS... – display name Dec 06 '21 at 17:36
3

Using lodash, you can do it like this:

export const toCamelCase = obj => {
  return _.reduce(obj, (result, value, key) => {
    const finalValue = _.isPlainObject(value) || _.isArray(value) ? toCamelCase(value) : value;
    return { ...result, [_.camelCase(key)]: finalValue };
  }, {});
};
Vincent D'amour
  • 3,746
  • 1
  • 27
  • 39
2

Well I took up the challenge and think I figured it out:

var firstToLower = function(str) {
    return str.charAt(0).toLowerCase() + str.slice(1);
};

var firstToUpper = function(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
};

var mapToJsObject = function(o) {
    var r = {};
    $.map(o, function(item, index) {
        r[firstToLower(index)] = o[index];
    });
    return r;
};

var mapFromJsObject = function(o) {
    var r = {};
    $.map(o, function(item, index) {
        r[firstToUpper(index)] = o[index];
    });
    return r;
};


// Map to
var contacts = [
    {
        GivenName: "Matt",
        FamilyName: "Berry"
    },
    {
        GivenName: "Josh",
        FamilyName: "Berry"
    },
    {
        GivenName: "Thomas",
        FamilyName: "Berry"
    }
];

var mappedContacts = [];

$.map(contacts, function(item) {
    var m = mapToJsObject(item);
    mappedContacts.push(m);
});

alert(mappedContacts[0].givenName);


// Map from
var unmappedContacts = [];

$.map(mappedContacts, function(item) {
    var m = mapFromJsObject(item);
    unmappedContacts.push(m);
});

alert(unmappedContacts[0].GivenName);

Property converter (jsfiddle)

The trick is handling the objects as arrays of object properties.

aloisdg
  • 22,270
  • 6
  • 85
  • 105
KyorCode
  • 1,477
  • 1
  • 22
  • 32
  • 1
    thats a nice solution! Both the alerts come out uppercase but I get the jist. The whole thing is bugging me, it messes up all my models/controllers if I do and if I dont change it. Its just a pain. Thanks. – Jon Wells Oct 17 '12 at 11:04
  • it's the property name that is now in camelcase notice the `.givenName` in map to and `.GivenName` in map from... It's confirmation that the property has changed name and not the value. – KyorCode Oct 17 '12 at 11:08
  • 1
    It's a design decision, it's the hard part of having a dynamic language. Apply certain conventions to yourself to keep everything in track :) – KyorCode Oct 17 '12 at 11:09
2

Here's handy library you might wanna try: https://www.npmjs.com/package/camelize2

You simply need to install it with npm install --save camelize2 and then

const camelize = require('camelize2')

const response = {
   Contacts: [{ GivenName: "Matt", FamilyName:"Berry" }]
}

const camelizedResponse = camelize(response)
Denis Ivko
  • 23
  • 3
1

I needed a generic method that accepted an array or object. This is what I'm using (I borrowed KyorCode's firstToLower() implementation):

function convertKeysToCamelCase(obj) {
    if (!obj || typeof obj !== "object") return null;

    if (obj instanceof Array) {
        return $.map(obj, function(value) {
            return convertKeysToCamelCase(value);
        });
    }

    var newObj = {};
    $.each(obj, function(key, value) {
        key = key.charAt(0).toLowerCase() + key.slice(1);
        if (typeof value == "object" && !(value instanceof Array)) {
          value = convertKeysToCamelCase(value);
        }
        newObj[key] = value;
    });

    return newObj;
};

Example calls:

var contact = { GivenName: "Matt", FamilyName:"Berry" };

console.log(convertKeysToCamelCase(contact));
// logs: Object { givenName="Matt", familyName="Berry"}

console.log(convertKeysToCamelCase([contact]));
// logs: [Object { givenName="Matt", familyName="Berry"}]

console.log(convertKeysToCamelCase("string"));
// logs: null

console.log(contact);
// logs: Object { GivenName="Matt", FamilyName="Berry"}
Irving
  • 1,257
  • 2
  • 16
  • 28
  • inside of the `$.each` loop, you should add `if (value instanceof Array) {value = convertKeysToCamelCase(value);}` to ensure that values that are Arrays can also be mapped – Norrec May 13 '16 at 05:48
  • Good point. Arrays work but non-array objects do not. I edited to support those. – Irving May 18 '16 at 15:27
1

Took the challenge with lodash and some es6+ features Here is my implementation with the reduce function.

function deeplyToCamelCase(obj) {
  return _.reduce(obj, (camelCaseObj, value, key) => {
    const convertedDeepValue = _.isPlainObject(value) || _.isArray(value)
      ? deeplyToCamelCase(value)
      : value;
    return { ...camelCaseObj, [_.camelCase(key)] : convertedDeepValue };
  }, {});
};
1

Use lodash ...

function isPrimitive (variable) {
  return Object(variable) !== variable
}

function toCamel (variable) {
  if (isPrimitive(variable)) {
    return variable
  }

  if (_.isArray(variable)) {
    return variable.map(el => toCamel(el))
  }

  const newObj = {}
  _.forOwn(variable, (value, key) => newObj[_.camelCase(key)] = toCamel(value))

  return newObj
}
1

Solution similar to @brandonscript, but in more ES6-functional way:

const camelCaseString = str => (
  (str.charAt(0).toLowerCase() + str.slice(1) || str).toString() 
);

const objectToCamelCase = val => {
  if (typeof val != 'object' || val === null) {
    return val;
  }
 
  if (val instanceof Array) {
    return val.map(objectToCamelCase);
  }
 
  return Object.keys(val)
    .filter(prop => val.hasOwnProperty(prop))
    .map(prop => ({[camelCaseString(prop)]: objectToCamelCase(val[prop])}))
    .reduce((prev, current) => ({...prev, ...current}))
};

// Example:
let converted = objectToCamelCase({UserId: 1, Hobbies: [{Id: 1, Label: "Read"}], Name: "John Doe"});

console.log(converted)
Denis Sedchenko
  • 168
  • 3
  • 9
1

you can do this simply by using json-case-convertor

const jcc = require('json-case-convertor')
const jsonData = ''//you json data to convert
const camelCasedJson = jcc.camelCaseKeys(jsonData) //Convert all the keys of object to snake case

This will handle all cascaded object as well

SWIK
  • 714
  • 7
  • 12
1

This function loop recursively through the object keys and using lodash returns a new object with every field converted to camelCase. It works also with arrays, nested arrays, nested objects.

function deepCamelCase (obj) {
  const c = {}

  if (typeof obj !== 'object') return obj

  _.mapKeys(obj, (v, k) => {
    let w = {}
  
    if (typeof v === 'object') {
      if (Array.isArray(v)) {
        const k = []
        for (const i of v) {
          k.push(deepCamelCase(i))
        }
      } else {
        _.mapValues(v, (n, m) => {
          if (Array.isArray(n)) {
            const k = []
            for (const i of n) {
              k.push(deepCamelCase(i))
            }
            w[_.camelCase(m)] = k
          } else {
            w[_.camelCase(m)] = deepCamelCase(n)
          }
        })
      }
    } else {
      w = v
    }
  
    c[_.camelCase(k)] = w
  })
  return c
}
0

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)

function snakeToCamelCase(snake_case_object){
  var camelCaseObject;
  if (isPlainObject(snake_case_object)) {        
    camelCaseObject = {};
  }else if(isArray(snake_case_object)){
    camelCaseObject = [];
  }
  forEach(
    snake_case_object,
    function(value, key) {
      if (isPlainObject(value) || isArray(value)) {
        value = snakeToCamelCase(value);
      }
      if (isPlainObject(camelCaseObject)) {        
        camelCaseObject[camelCase(key)] = value;
      }else if(isArray(camelCaseObject)){
        camelCaseObject.push(value);
      }
    }
  )
  return camelCaseObject;  
}
0

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) or null:

function convertPropertiesToCamelCase(instance) {
    if (instance instanceof Array) {
        var result = [];

        for (var i = 0; i < instance.length; i++) {
            result[i] = convertPropertiesToCamelCase(instance[i]);
        }

        return result;
    }

    if (typeof instance != 'object') {
        return instance;
    }

    var result = {};

    for (var key in instance) {
        if (!instance.hasOwnProperty(key)) {
            continue;
        }

        result[key.charAt(0).toLowerCase() + key.substring(1)] = convertPropertiesToCamelCase(instance[key]);
    }

    return result;
}
0

Building on goredwards answer (which didn't handle the array fields correctly)

function objectKeysToCamelCase(snake_case_object) {
  let camelCaseObject = {}
  _.forEach(
    snake_case_object,
    function(value, key) {
      if (_.isPlainObject(value)) {
        value = objectKeysToCamelCase(value)
      } else if (_.isArray(value)) {
        value = value.map(v => _.isPlainObject(v) ? objectKeysToCamelCase(v) : v)
      }
      camelCaseObject[_.camelCase(key)] = value
    },
  )
  return camelCaseObject
}
Guy
  • 1,254
  • 17
  • 16
0

here is code I found for it, not fully tested though, but worth sharing. It is far more readable than other answers, not sure about performance.

test it http://jsfiddle.net/ms734bqn/1/

const toCamel = (s) => {
      return s.replace(/([-_][a-z])/ig, ($1) => {
        return $1.toUpperCase()
          .replace('-', '')
          .replace('_', '');
      });
    };

const isArray = function (a) {
  return Array.isArray(a);
};

const isObject = function (o) {
  return o === Object(o) && !isArray(o) && typeof o !== 'function';
};

const keysToCamel = function (o) {
  if (isObject(o)) {
    const n = {};

    Object.keys(o)
      .forEach((k) => {
        n[toCamel(k)] = keysToCamel(o[k]);
      });

    return n;
  } else if (isArray(o)) {
    return o.map((i) => {
      return keysToCamel(i);
    });
  }

  return o;
};
dzona
  • 3,323
  • 3
  • 31
  • 47
0

Pure JavaScript, shoud work fine

function convertKeysToCamelCase(object) {
    if(object === undefined || object === null || typeof object !== "object") {
        return object;
    } else {
        if(Array.isArray(object)) {
            return object.map(item => convertKeysToCamelCase(item));
        } else {
            return Object.entries(object).reduce((result, [key, value]) => {
                result[key.charAt(0).toLowerCase() + key.slice(1)] = convertKeysToCamelCase(value);
                return result;
            }, {});
        }
    }
}
0

Datawaeve Script to Convert Nested JSON Keys into Camcel Case

%dw 2.0
output application/json
import * from dw::core::Objects
import * from dw::core::Strings
fun toCamelCase(str: String) = camelize(str)
fun convertKeys(obj: Any): Any =
    obj match {
    case is Object -> 
            obj mapObject ((value, key) -> 
                {
        (toCamelCase(key)): convertKeys(value)
    }
            )
        case is Array ->
            obj map convertKeys($)
        else -> obj
}
---
convertKeys(payload)
ARAVIND
  • 51
  • 1
  • 8
0

I was looking for camelCase to Pascalcase. My object is camelCase and need to convert it to Pascalcase based on the C# class property name.

Here I have modified the method,

var toPascalCase = function (Object) {
    var NewObject, origKey, newKey, value
    if (Object instanceof Array) {
        return Object.map(function (value) {
            if (typeof value === "object") {
                value = toPascalCase(value)
            }
            return value
        })
    } else {
        NewObject = {}
        for (origKey in Object) {
            if (Object.hasOwnProperty(origKey)) {
                newKey = (origKey.charAt(0).toUpperCase() + origKey.slice(1) || origKey).toString()
                value = Object[origKey]
                if (value instanceof Array || (value !== null && value.constructor === Object)) {
                    value = toPascalCase(value)
                }
                NewObject[newKey] = value
            }
        }
    }
    return NewObject
}

Get Output:

console.log(result);
result = toPascalCase(result);
console.log(result);

Here result is my object.

Before Conversion:

{
    "id": 187,
    "fromUserId": 1,
    "fromUserFullName": "Super Admin",
    "toUserId": 3,
    "toUserFullName": "Super Admin",
    "message": "Hello",
    "isMessageFromUser": true,
    "isRead": false,
    "messageTime": "Thu Aug 03,2023,2:58 PM",
    "fromUserOnlineStatus": "Online",
    "toUserOnlineStatus": "Online",
    "createdDate": "0001-01-01T00:00:00",
    "modifiedDate": "0001-01-01T00:00:00",
    "createdBy": null,
    "modifiedBy": null,
    "cancelled": false
}

After Conversion:

{
    "Id": 187,
    "FromUserId": 1,
    "FromUserFullName": "Super Admin",
    "ToUserId": 3,
    "ToUserFullName": "Super Admin",
    "Message": "Hello",
    "IsMessageFromUser": true,
    "IsRead": false,
    "MessageTime": "Thu Aug 03,2023,2:58 PM",
    "FromUserOnlineStatus": "Online",
    "ToUserOnlineStatus": "Online",
    "CreatedDate": "0001-01-01T00:00:00",
    "ModifiedDate": "0001-01-01T00:00:00",
    "CreatedBy": null,
    "ModifiedBy": null,
    "Cancelled": false
}
-1

Convert object keys to camelCase with deep.

import _ from 'lodash';

export function objectKeysToCamelCase(entity) {
    if (!_.isObject(entity)) return entity;

    let result;

    result = _.mapKeys(entity, (value, key) => _.camelCase(key));
    result = _.mapValues(result, (value) => objectKeysToCamelCase(value));

    return result;
}