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