Below is an example of my data object structure:
const courses = [
{
degree: 'bsc',
text: 'Some text',
id: 'D001',
},
{
degree: 'beng',
text: 'Some text',
id: 'D002',
},
{
degree: 'bcom',
text: 'Some text',
id: 'D003',
electives: [
{
degree: 'bsc',
course: 'Psychology'
text: 'Some text',
id: 'C010',
},
],
},
];
I want to update the text
property in all objects, including those nested in arrays. The desired format looks like this:
const courses = [
{
degree: 'bsc',
text: translateText('D001'),
id: 'D001',
},
{
degree: 'beng',
text: translateText('D002'),
id: 'D002',
},
{
degree: 'bcom',
text: translateText('D003'),
id: 'D003',
electives: [
{
degree: 'bsc',
course: 'Psychology'
text: translateText('C010'),
id: 'C010',
},
],
},
];
I aim to achieve this transformation by passing the Id property as a parameter. Below is my current method:
courses.forEach(course => {
course.text = translateText(course.id);
if (course.degree === 'bcom') {
course.electives.forEach(elective => {
elective.text = translateText(elective.id);
})
}
});
I am not entirely satisfied with this approach as it could become cluttered if more arrays are added to different degree types. Additionally, I am concerned about potential performance implications. Is there a cleaner and better way to accomplish this?