首页 > 解决方案 > 从嵌套对象数组返回类似文件夹的路径

问题描述

我有一组嵌套对象。它们代表类似文件夹的路径或带有子导航的菜单。

结构如下:

const MENU:Menu[] = [
  {
    value: 'Home',
    nested: [
      { value: 'home-1', url: 'home-1' },
      { value: 'home-2', url: 'home-2' },
    ],
  },

  {
    value: 'about',
    nested: [
      {
        value: 'about-1',
        url: 'about-1',
      },
      {
        value: 'about-2',
        url: 'about-2',
      },
    ],
  },
];

我希望给定的url使用value属性返回路径。

例如,对于home-1=>['Home','home-1']

对于about-2=>['about','about-2']

这个菜单的界面是

interface Menu {
  value: string;
  nested?: Menu[];
  url?: string;
}

这是我尝试过的

function getPath(url, menu = MENU, navTreePath = []) {
  for (let i = 0; i < menu.length; i++) {
    const currentMenu = menu[i];

    if (currentMenu.url === url) {
      navTreePath.push(currentMenu.value);
      return navTreePath;
    } else if (currentMenu.nested) {
      navTreePath.push(currentMenu.value);
      return getNavTreePathFromUrl(url, currentMenu.nested, []);
    } else {
    }
  }
}

和电话

const path = getPath('about-2');

标签: javascriptarraysloopsobjectnested

解决方案


您将需要递归算法来爬取整个深度:

const menu = [
  {
    value: 'Home',
    nested: [
      { value: 'home-1', url: 'home-1' },
      { value: 'home-2', url: 'home-2' },
    ],
  },

  {
    value: 'about',
    nested: [
      {
        value: 'about-1',
        url: 'about-1',
      },
      {
        value: 'about-2',
        url: 'about-2',
        nested: [
          {
            value: 'detailed about',
            url: 'detailedAbout'
          }
        ]
      },
    ],
  },
],
      
      getPath = (tree, needle, path=[]) => 
        tree.reduce((acc, {url, value, nested=[]}) => {
          if(url == needle){
            acc.push(...path, value)
          } else if (!!nested.length) {
            acc.push(...getPath(nested, needle, [...path, value]))
          }
          return acc
        }, [])

console.log(getPath(menu, 'detailedAbout'))
        
      


推荐阅读