I am currently in a situation where there are certain properties in an object that I would like to change to snake case. At the moment I can change the names of properties in this object if they are not in a nested object or in an object in an array. This is my function along with the object I'm passing in:
/* an object to refer to where the values are what I want to change the name to */
const camelToSnake = {
accountId: 'id',
taxId: 'tax_id',
individuals: 'customers',
firstName: 'first_name',
lastName: 'last_name',
};
/* example object I am passing in to the function */
const obj = {
accountId: "12345",
individuals: [
{name: {firstName: "John", lastName: "Doe"}},
{name: {firstName: "Bob", lastName: "Smith"}},
],
taxId: "67890",
}
const restructureToSnakeCase = obj => {
const newObj = {};
Object.keys(obj).forEach(key => {
if(typeof obj[key] === 'object'){
restructureToSnakeCase(obj[key])
}
if(Array.isArray(obj[key])){
obj[key].map(el => {
restructureToSnakeCase(obj[key])
})
}
newObj[camelToSnake[key] || key] = obj[key]
});
return newObj;
};
With my function so far, it is able to loop over any first level objects and change the property names, but isn't with any nested value.
With the object I pass in above this is the result:
{
id: "12345",
customers: [
{name: {firstName: "John", lastName: "Doe"}},
{name: {firstName: "Bob", lastName: "Smith"}},
],
tax_id: "67890"
}
In this situation, "firstName" and "lastName" should be "first_name" and "last_name".
I thought with the recursion I have above, that it would be able to go into every nested object and change the property names accordingly, but evidently this is not working. I'd really appreciate any pointers.