Home > Software engineering >  How to find and remove all underscores, and make the next letter after the underscore uppercase
How to find and remove all underscores, and make the next letter after the underscore uppercase

Time:08-31

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 }

CodePudding user response:

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() || ``)

CodePudding user response:

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.

CodePudding user response:

I would do something like this. Use split and a regex to match underscores to create array of words. Filter out any zero-character "words" (which would happen if the prop started with an underscore). Then if the word is not the first in the array, capitalize it, and rejoin into one string. If the prop has been transformed, set the new prop and delete the old one.

function capital(string) {
  return string.charAt(0).toUpperCase()   string.slice(1);
}

const obj = {
  api_key: 1,
  is_auth: false,
  something_____else: true,
  ay_be_see: false,
  _test: "started with underscore",
  keepme: "keep this one as is",
  i_end_with_an_underscore_: "ending underscore"
};

for (let oldKey in obj) {
  const newKey = oldKey.split(/[_] /g)
    .filter(word => word)
    .map((word, index) => index === 0 ? word : capital(word))
    .join('');
  if (newKey !== oldKey) {
    obj[newKey] = obj[oldKey];
    delete obj[oldKey];
  }
}




console.log(obj);

  • Related