查找數組「樹」的全部路徑

需求

導航欄或者菜單欄組件,元數據從最外層到 target vlaue 的路徑上文案所有高亮 。因此須要找出通過 target vlaue 的路徑有哪些?優化

例子

  1. 元數據數據結果以下:
const dataSource = [
  {
    label: '首頁',
    value: 1,
  },
  {
    label: '商品分類',
    value: 2,
    child: [
      {
        label: '服飾',
        value: 21,
        child: [
          {
            label: '精美女裝',
            value: 211,
          },
        ],
      },
      {
        label: '地方特產',
        value: 22,
        child: [
          {
            label: '河南特產',
            value: 221,
            child: [
              {
                label: '方中山胡辣湯',
                value: 2211,
              },
              {
                label: '燴麪',
                value: 2212,
              },
            ],
          },
          {
            label: '上海特產',
            value: 222,
          },
        ],
      }
    ]
  },
  {
    label: '個人',
    value: 3,
    child: [
      {
        label: '基本信息',
        value: 31,
      },
      {
        label: '個人訂單',
        value: 33,
        child: [
          {
            label: '所有訂單',
            value: 331,
          },
          {
            label: '待收貨',
            value: 332,
          },
        ],
      }
    ]
  }
]
  1. 查找出該元數據全部的路徑:
/**
 * 獲取全部路徑
 */
const getAllValuePaths = (dataSource) => {
  let result = []
  if (!dataSource || dataSource.length ===0) return []

  const constructPaths = (data, path) => {
    data.forEach(({ value, child }) => {
      path.push(value)
      if (!child || child.length === 0) {
        result.push(JSON.parse(JSON.stringify(path)))
      } else {
        constructPaths(child, path)
      }
      path.pop()
    })
  }

  constructPaths(dataSource, [])
  return result
}
  1. 優化全部路徑方法,找出指定 target value 的路徑:
/**
 * 獲取指定 target 路徑
 */
const getValuePathsByTarget = (dataSource, target) => {
  let result = []
  if (!dataSource || dataSource.length ===0 || !target) return []

  const constructPaths = (data, target, path) => {
    data.forEach(({ value, child }) => {
      path.push(value)
      if (value === target) {
        result = JSON.parse(JSON.stringify(path))
        return
      }
      if (child && child.length) {
        constructPaths(child, target, path)
      }
      path.pop()
    })
  }

  constructPaths(dataSource, target, [])
  return result
}
  1. 自測結果:

相關文章
相關標籤/搜索