I am currently working on transforming an array object into a new object, where some keys are renamed and the rest of the keys are converted to camelCase.
For example:
1. Renaming Keys
The key orgId
will be renamed to clientDivisionOrganizationId
.
2. Converting Key Cases
All other keys will be converted from snake_case to camelCase, except for a specific scenario with nested arrays like address_usages
, which presents a unique challenge for conversion.
I have explored various solutions but would greatly appreciate any help or insights.
Thank you
const originalArray =[{
// array contents here
}];
// define transformation rules
const newKeyMap={
// key mappings here
};
function camelize(text) {
// function logic for camelize
}
// function to transform array object using defined rules
const transformArrayObject=(originalArray, newKeyMap)=>{
return originalArray.map(obj => {
const transformedObj = Object.entries(obj).reduce((acc, [key, value]) =>{
if (typeof value === "object" && !Array.isArray(value) && value!==null) {
const nestedObj = Object.entries(value).reduce((nestedAcc, [nestedKey, nestedValue]) =>{
const newNestedKey = newKeyMap[`${camelize(key)}.${camelize(nestedKey)}`] || camelize(nestedKey);
nestedAcc[camelize(newNestedKey)] = nestedValue;
return nestedAcc;
}, {});
acc[camelize(key)] = nestedObj;
} else if (Array.isArray(value) && value.length>0) {
acc[camelize(key)] = value.map(nestedObj =>{
return Object.entries(nestedObj).reduce((nestedAcc, [nestedKey, nestedValue]) =>{
const newNestedKey = newKeyMap[`${key}.${camelize(nestedKey)}`] || nestedKey;
nestedAcc[camelize(newNestedKey)] = nestedValue;
return nestedAcc;
}, {});
});
} else {
const newKey = newKeyMap[camelize(key)] || camelize(key);
acc[newKey] = value;
}
return acc;
}, {});
return transformedObj;
});
}
console.log("Result:",transformArrayObject(originalArray,newKeyMap));