当前位置:主页 > 查看内容

查找数组“树”的所有路径

发布时间:2021-07-13 00:00| 位朋友查看

简介:需求 导航栏或者菜单栏组件,元数据从最外层到 target vlaue 的路径上文案全部高亮 。所以需要找出经过 target vlaue 的路径有哪些? 例子 元数据数据结果如下: const dataSource = [ { label: '首页', value: 1, }, { label: '商品分类', value: 2, child:……

需求

导航栏或者菜单栏组件,元数据从最外层到 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. 自测结果:


本文转自网络,版权归原作者所有,原文链接:https://segmentfault.com/a/1190000040339852
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:Equinix8.74亿美元出售8个数据中心 下一篇:没有了

推荐图文


随机推荐