Skip to content

Instantly share code, notes, and snippets.

@signalwerk
Created June 10, 2020 15:19
Show Gist options
  • Save signalwerk/553a52d05fa62227051ca4e44cd343ad to your computer and use it in GitHub Desktop.
Save signalwerk/553a52d05fa62227051ca4e44cd343ad to your computer and use it in GitHub Desktop.
set menu items to active based on children
// this is the original menu-structure
let menu = {
children: [
{ path: "/node/1", title: "Title 1" },
{
path: "/node/2",
title: "Title 2",
children: [
{ path: "/node/21", title: "Title 2.1" },
{ path: "/node/22", title: "Title 2.2" }
]
}
]
};
// check abstraction
const isActive = (item, path) => item.path === path;
// set an 'active' key on each object if
// a child is active
const setActive = (menu, path) => {
// the returned menu
let newMenu = {
...menu
};
// is this menu active
let subActive = false;
// children check
if (menu.children) {
newMenu.children = [];
menu.children.forEach(item => {
let { active, menu } = setActive(item, path);
if (active) {
subActive = true;
}
newMenu.children.push(menu);
});
}
// if one of the children is active or the item itself
newMenu.active = subActive || isActive(menu, path);
// return
return {
active: newMenu.active,
menu: newMenu
};
};
// the new menu is here
const result = setActive(menu, "/node/22");
// print
console.log(JSON.stringify(result, null, 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment