Answer the question
In order to leave comments, you need to log in
How to convert object property names from kebab-case to camelCase?
I need to rewrite my old function according to the imperative approach. The meaning of the function - when receiving data from the server, all object properties (as well as nested ones) are renamed from ke_bab to camelCase. An example of an old function, everything worked:
export const convertKeysToCamelCaseOrRemove = (
responseData: { [key: string]: any },
except?: Array<string>
) => {
const keys = Object.keys(responseData);
keys.forEach((key) => {
if (typeof responseData[key] === 'object' ) {
convertKeysToCamelCaseOrRemove(responseData[key]);
}
const oldKeyArray: Array<string> | string = key.replace('__', '_').split('_');
let newKeyArray: Array<string> = [];
if (oldKeyArray.length === 1) {
newKeyArray.push(oldKeyArray.toString());
}
const firstKeyWord: Array<string> = [];
const restKeyWord: Array<string> = [];
oldKeyArray.map((oldKey: string) => {
if (oldKeyArray.indexOf(oldKey) === 0) {
firstKeyWord.push(oldKey);
return firstKeyWord;
}
const newKey = oldKey[0].toUpperCase() + oldKey.slice(1);
restKeyWord.push(newKey);
return restKeyWord;
});
newKeyArray = [...firstKeyWord, ...restKeyWord];
const newKey = newKeyArray.join('');
if (newKey !== key) {
delete Object.assign(responseData, { [newKey]: responseData[key] })[key];
}
except &&
except.forEach((exceptKey) => {
if (newKey === exceptKey) {
delete Object.assign(responseData)[exceptKey];
}
});
return newKeyArray;
});
return responseData;
};
export const convertKeysToCamelCaseOrRemove = (
responseData: { [key: string]: any },
) => {
const newArr = responseData && Object.entries(responseData).map((item) => {
const key = item[0];
const value = item[1];
if (typeof value === 'object' && value !== null && value !== undefined && value.length ) {
value.map((item123:any) =>convertKeysToCamelCaseOrRemove(item123));
}
let arrKey = key.replace('__', '_').split('_');
if (arrKey.length > 1) {
const first = arrKey[0];
const old = arrKey.splice(1).map((oldKey => oldKey.charAt(0).toUpperCase() + oldKey.substring(1)));
arrKey = [first, ...old];
}
return [arrKey.join(''), value];
});
return Object.fromEntries(newArr);
};
Answer the question
In order to leave comments, you need to log in
const toCamelCase = val =>
val instanceof Array
? val.map(toCamelCase)
: val instanceof Object
? Object.fromEntries(Object
.entries(val)
.map(n => [
n[0].replace(/_+(.)/g, (m, g1) => g1.toUpperCase()),
toCamelCase(n[1]),
])
)
: val;
Changed so, does not work in some cases
if (typeof value === 'object' && value !== null && value !== undefined && value.length ) {
value = [...value.map((item1:any) => convertKeysToCamelCaseOrRemove(item1)
)];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question