I have to manipulate a nested object. Here's my code:
function modify(object) {
Object.keys(object).forEach(key => {
if (typeof object[key] === 'object') {
if (object[key].class && object[key].type && object[key].period) {
object[key].applicableName = `${object[key].class}|${object[key].type}|${object[key].period}`;
delete object[key].class;
delete object[key].type;
delete object[key].period;
} else {
modify(object[key]);
}
}
});
}
Here's the object:
[
{
"item": [
{
"period": "period-CYTM",
"type": "type-CMLT",
"class": "class-RFEE",
},
{
"period": "period-FYTD",
"type": "type-CMLT",
"class": "class-RFEE",
},
{
"period": "period-ITD",
"type": "type-ANNL",
"class": "class-RFEE",
},
{
"period": "period-ITD",
"type": "type-CMLT",
"class": "class-RFEE",
},
{
"period": "period-1MTH",
"type": "type-CMLT",
"class": "class-RFEE",
},
{
"period": "period-1YR",
"type": "type-CMLT",
"class": "class-RFEE",
},
{
"period": "period-10YR",
"type": "type-ANNL",
"class": "class-RFEE",
},
{
"period": "period-10YR",
"type": "type-CMLT",
"class": "class-RFEE",
}
]
}
]
It is working fine, but the issue is that it is mutating the original object. How can I make my modify
method return a new modified object and the original object remains intact?
I tried to clone the original object and then passed the cloned object to the modify
method, but, that was not an elegant solution in my opinion.