映射嵌套数组并返回匹配的元素。

3

我知道,已经有很多相同的问题,我看过其中一些,但是没有得到完整的答案。

因此,我有一个数组,类似于这样(为了演示而简化):

// links.js

const links = [
 {
  name: 'Page 1',
  path: '/page-1'
 },
 {
  name: 'Page-2',
  subpages:[
   { name: 'Page (2-1)', path: '/page-2-1' },
   { name: 'Page (2-2)', path: '/page-2-2' }
  ]
 },
 {
  name: 'Page 3',
  path: '/page-3'
 },
 {
  name: 'Page 4',
  subpages:[
   { name: 'Page (4-1)', path: '/page-4-1' },
   { name: 'Page (4-2)', path: '/page-4-2' },
   { name: 'Page (4-3)', path: '/page-4-3' }
  ]
 },
 ...
]
export default links

上面的对象是菜单链接数据,我在屏幕上呈现它们以在页面之间进行导航,subpages是下拉菜单。它们具有路径或子页面中的一个,不能同时具有两者,并且可能更深嵌套。
我需要帮助解决以下2个任务。
第一个:
我的网站每个页面都有标题,大多数标题与上面显示的名称属性相同。
因此,我在每个页面上呈现一个函数,返回当前路由的路径名,所以我想对links进行映射并获取匹配path的name属性。 例如,如果我输入/page-4-1,则要获取匹配路径的name属性。这样就是name:Page 4。
第二个:
这次是类似于面包屑导航,如果我输入['/page-1','/page-2-1','/page-4-2'],我想要得到:
[
 {
  name: 'Page 1',
  path: '/page-1'
 },
 { 
  name: 'Page (2-1)',
  path: '/page-2-1' 
 },
 { 
  name: 'Page (4-2)',
  path: '/page-4-2' 
 },
]

有些情况下可能找不到匹配结果,在这种情况下,我想插入{name: document.body.title, path: null}

我尝试了

我正在使用Next.js

import { useRouter } from 'next/router'
import links from 'links.js'

const router = useRouter()
const splitted = router.asPath
      .split('/')
      .filter(
        (sp) =>
          sp !== ''
      )

cost ready = []

for (let sp = 0; sp < splitted.length; sp++) {
      for (let ln = 0; ln < links.length; ln++) {
        if (links[ln].path) {
          if (links[ln].path === '/' + splitted[sp]) {
            ready.push(links[ln])
          }
        } else {
          for (let sb = 0; sb < links[ln].sublinks.length; sb++) {
            if (links[ln].sublinks[sb].path === '/' + splitted[sp]) {
              ready.push(links[ln].sublinks[sb])
            }
          }
        }
      }
    }

这部分代码有些可行,但有点混乱。使用 map, filterfind 应该会有更好的方法,但我尝试了很多次都没有成功。

感谢您提前的帮助!

编辑:

糟糕!我的问题有一个大错误,links 对象只包含 path 键,而不是条件性的 pathlink

2个回答

1

const links = [
 {
  name: 'Page 1',
  path: '/page-1'
 },
 {
  name: 'Page-2',
  subpages:[
   { name: 'Page (2-1)', path: '/page-2-1' },
   { name: 'Page (2-2)', path: '/page-2-2' }
  ]
 },
 {
  name: 'Page 3',
  path: '/page-3'
 },
 {
  name: 'Page 4',
  subpages:[
   { name: 'Page (4-1)', path: '/page-4-1' },
   { name: 'Page (4-2)', path: '/page-4-2' },
   { name: 'Page (4-3)', path: '/page-4-3' }
  ]
 },
];
const findPathObj = (path,links) => {
    let result = null;
    for(const item of links){
      if(item.path == path) return item;
      if(item.subpages) result = findPathObj(path, item.subpages)
      if(result) break;  
   }
  return result;
}
const findPageName = (path,links) => findPathObj(path,links)?.name;
const findBreadcrumb = (pathes, links) => pathes.map(path => findPathObj(path,links) || {name: document.title, path: null});

console.log(findPageName('/page-4-1', links));
console.log(findBreadcrumb(['/page-1', '/page-2-1', '/page-4-2'],links))


0

针对您的第一个问题,请尝试以下方法

const links = [
  {
    name: "Page 1",
    path: "/page-1",
  },
  {
    name: "Page-2",
    subpages: [
      { name: "Page (2-1)", path: "/page-2-1" },
      { name: "Page (2-2)", path: "/page-2-2" },
    ],
  },
  {
    name: "Page 3",
    link: "/page-3",
  },
  {
    name: "Page 4",
    subpages: [
      { name: "Page (4-1)", link: "/page-4-1" },
      { name: "Page (4-2)", link: "/page-4-2" },
      { name: "Page (4-3)", link: "/page-4-3" },
    ],
  },
];

// Find out function
// Level must 0 at beginning
function findout(pages, search, level = 0) {
  for (const page of pages) {
    if (page.link === search || page.path === search) {
      if (level === 0) {
        return page.name;
      }

      return true;
    }

    if (Array.isArray(page.subpages)) {
      if (findout(page.subpages, search, level + 1)) {
        if (level === 0) {
          return page.name;
        }

        return true;
      }
    }
  }

  return false;
}

console.log(findout(links, "/page-4-3"))

第二个问题我建议这样做

const links = [
  {
    name: "Page 1",
    path: "/page-1",
  },
  {
    name: "Page-2",
    subpages: [
      { name: "Page (2-1)", path: "/page-2-1" },
      { name: "Page (2-2)", path: "/page-2-2" },
    ],
  },
  {
    name: "Page 3",
    link: "/page-3",
  },
  {
    name: "Page 4",
    subpages: [
      { name: "Page (4-1)", link: "/page-4-1" },
      { name: "Page (4-2)", link: "/page-4-2" },
      { name: "Page (4-3)", link: "/page-4-3" },
    ],
  },
];

function findout2(pages, search, result = []) {
  for (const page of pages) {
    if (typeof page.link === "string" && search.includes(page.link)) {
      result.push({ name: page.name, link: page.link });
    } else if (typeof page.path === "string" && search.includes(page.path)) {
      result.push({ name: page.name, path: page.path });
    }

    if (Array.isArray(page.subpages)){
      findout2(page.subpages, search, result)
    }
  }

  return result
}

console.log(findout2(links, ['/page-1', '/page-2-1', '/page-4-2']))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接