I am facing a challenge with a complex data object that includes nested objects and arrays, making it difficult to replace the value of all occurrences of link
in the attributes object. The data is returned as a single large blob, and I'm struggling to come up with a flexible solution that can traverse through objects and arrays to check for the existence of link
.
Let me provide an example of the data:
const data = {
components: [
{
name: 'header',
attributes: {
messageBars: [],
link: '/new-link/'
navigation: {
brand: {
link: '/',
alt: 'blah',
},
},
},
},
{
name: 'body',
attributes: {
header: {
text: 'blah',
},
buttons: [
{
children: 'OK!',
link: '/new-link/',
},
],
},
},
I have managed to access the attributes layer but struggled with implementing a recursive function called readData.
const replaceLink = (newLink: string, data: object) => {
data.components.forEach(component => {
if(component.attributes) readData(component.attributes, newLink);
});
return data;
};