I am looking into a code which is to strip some prefix url from object properties.
const strip2 = (object, path) => {
const keys = [path];
const pathArray = keys[0].split('.');
pathArray.reduce((prevObj, key, index) => {
if (!prevObj[key]) {
return null;
}
if (Array.isArray(prevObj[key])) {
return prevObj[key].map(item => strip2(item, pathArray[index + 1]));
}
if (index === pathArray.length - 1) {
prevObj[key] = prevObj[key].replace('/hello', '');
}
}, object);
return object;
};
strip2(
{
title: 'this is the title',
menu: [
{
link: '/hello/contact',
title: 'Contact Us',
},
{
link: '/hello/faq',
title: 'Faq',
},
],
},
'menu.link'
);
\ it will return
{
title: 'this is the title',
menu: [
{ link: '/contact', title: 'Contact Us' },
{ link: '/faq', title: 'Faq' }
]
}
I tried to trace it and I can’t understand how does the replace method inside reduce affects the object in outer scope.