1

i have object with underscores keys

const obj = { api_key: 1, is_auth: false }

i want to get camelCase keys

const obj = { apiKey: 1, isAuth: false }

Slava
  • 25
  • 1
  • 2
  • Do you want to mutate the object, or create an entirely new object with the new keys? – Andy Aug 30 '22 at 16:04

2 Answers2

0

RegEx can change the casing, and then the converted keys must be put in the object:

const obj = { api_key: 1, is_auth: false } // your sample data

for(let key in obj) {
    let newKey = key.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
    if(newKey!=key) {
        obj[newKey] = obj[key];
        delete obj[key];
    }
}
      

The inner if takes care of preserving any key in obj that should not follow Snake Case.

Alex
  • 23,004
  • 4
  • 39
  • 73
0

You can map the keys using a regular expression to replace the underscores and following character with an uppercased character. Something like:

const obj = {
  api_key: 1,
  is_true: false,
  all___under_scores: true,
  _test: "Tested",
  test_: "TestedToo (nothing to replace)",
};
const keys2CamelCase = obj => Object.fromEntries(
  Object.entries(obj)
  .map(([key, value]) => 
    [key.replace(/_{1,}([a-z])/g, (a, b) => b.toUpperCase()), value])
);

console.log(keys2CamelCase(obj));

If you also want to remove trailing underscores use

key.replace(/_{1,}([a-z])|_$/g, (a, b) => b && b.toUpperCase() || ``)
KooiInc
  • 119,216
  • 31
  • 141
  • 177