Home > OS >  Map an nested arrays and return matched ones
Map an nested arrays and return matched ones

Time:12-26

I know, there are already tons of same questions i saw some of them, but couldn't get full answer.

So, I have an array something like this (simplified for demonstration):

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

The above object is menu-links data, i render them on the screen for nagivating between pages and subpages is dropdown. They have either path or subpages, not both and there might be more nested.

There are 2 tasks i want help with.

First:

Every page of my site has a title and most of them is same as its name property shown above.

So, i have a function rendered on every page that returns the pathname of the current route, so what i want is to map through the links and get the name of matched path.
For example, if i give /page-4-1, i wanna get the name property of the matched path, So that is name: Page 4

Second

This time, it is something like a breadcrumb, If i give ['/page-1', '/page-2-1', '/page-4-2'], i wanna get:

[
 {
  name: 'Page 1',
  path: '/page-1'
 },
 { 
  name: 'Page (2-1)',
  path: '/page-2-1' 
 },
 { 
  name: 'Page (4-2)',
  path: '/page-4-2' 
 },
]

There will be cases where there might not be a matched result, in that case i would like to insert {name: document.body.title, path: null}

I tried

i'm using 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])
            }
          }
        }
      }
    }

This is partly working but is messy, there should be a better ways with map, filter and find but i couldn't succeed with my tries on them.

Thank you in advance for your help!

EDIT:

Oops! my question had a big mistake, the links object only contains path key, not conditional path and link.

CodePudding user response:

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

CodePudding user response:

For your first question try the following

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

The second question I suggest this

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

  • Related