So there are plenty of questions that go over how to loop through an object and make a simple change to a property name, but what I'm trying to tackle is a tad trickier and would greatly appreciate some help.
Essentially, I want to make an object like this:
{
home_number: '1234',
customer: {
name: {
last_name: 'Smith',
},
},
};
turn into this
{
home_number: '1234',
individual: {
name: {
lastName: 'Smith',
},
},
};
At the moment, my function is as follows
function restructure(obj) {
let newObj = {};
const newKeys = {
fed_tax_id: 'federalTaxId',
company_structure: 'companyStructure',
home_number: 'homeNumber',
customer: 'individual',
first_name: 'firstName',
last_name: 'lastName',
}
}
for(let key in obj){
if (typeof obj[key] === 'object') {
restructure(obj[key])
}
if(Object.hasOwnProperty.call(newKeys, key)){
let newProperty = newKeys[key]
newObj[newProperty] = obj[key]
}
if(!Object.hasOwnProperty.call(newKeys, key)){
newObj[key] = obj[key]
}
return newObj;
}
One thing I'm struggling with at the moment is removing the keys that need to be changed (I created the newKeys object as a way to show the keys that need to change and what they need to be changed to). I.e. in this case when customer is changed to individual, it will also change 'last_name' to 'lastName'.
With my function the way it is at the moment, the object comes back just as:
{ homeNumber: '1234' }
Thank you :) If this has been asked already please let me know, but after searching all over the place I wasn't able to find a question close enough to this.