I need assistance in developing a function that can determine whether the link ID of an object or any of its children match a specific ID. For instance, if the link ID for Product paths is 51125095, the function should return true when this ID is passed into it.
Below is a sample object:
const sampleObj = {
id: '55259494',
menuText: 'Top level link',
link: {
id: '55259472',
slug: 'lop-level-link',
},
children: [
{
id: '53664310',
menuText: 'Product paths',
link: {
id: '51125095',
slug: 'product-paths',
},
children: [],
},
{
id: '53664355',
menuText: 'Testing',
link: {
id: '51272081',
slug: 'testing',
},
children: [],
},
{
id: '53664382',
menuText: 'Relay',
link: {
id: '51489535',
slug: 'relay',
},
children: [],
},
{
id: '55259577',
menuText: 'About us',
link: {
id: '55259487',
slug: 'about-us',
},
children: [],
},
],
}
The initial implementation of the function is as follows:
const isObject = (value) => {
return !!(value && typeof value === 'object' && !Array.isArray(value))
}
const containsActiveLink = (linkObject = {}, pageIDToMatch) => {
if (isObject(linkObject)) {
console.log('Run:' + linkObject.menuText)
console.log(linkObject)
if (linkObject.link.id === pageIDToMatch) {
return true
}
if (linkObject.children.length > 0) {
linkObject.children.map((child) => containsActiveLink(child, pageIDToMatch))
}
}
return false
}
const isActiveLink = containsActiveLink(sampleObj, '51125095')
Your support with refining this function would be highly appreciated. Thank you!