【问题标题】:Map an nested arrays and return matched ones映射嵌套数组并返回匹配的数组
【发布时间】:2022-01-25 12:59:55
【问题描述】:

我知道,我已经看到了很多相同的问题,但无法得到完整的答案。

所以,我有一个类似这样的数组(为演示而简化):

// 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 是下拉菜单。它们有 pathsubpages,不是两者都有,可能还有更多嵌套。

有 2 个任务我需要帮助。

第一:

我网站的每个页面都有一个标题,其中大部分与上面显示的 name 属性相同。

所以,我在每个页面上都呈现了一个函数,该函数返回当前路由的路径名,所以我想要通过links 进行映射并获得匹配的namepath
比如我给/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}

我试过了

我正在使用 Nextjs

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])
            }
          }
        }
      }
    }

这部分工作但很混乱,mapfilterfind 应该有更好的方法,但我无法成功尝试它们。

提前感谢您的帮助!

编辑:

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

【问题讨论】:

    标签: javascript arrays filter


    【解决方案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",
        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']))

    【讨论】:

      【解决方案2】:

      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))

      【讨论】:

        猜你喜欢
        • 2021-11-21
        • 2019-08-13
        • 2013-11-28
        • 2021-05-27
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        • 2016-04-10
        • 2013-08-08
        相关资源
        最近更新 更多