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

摘要:导航栏或者菜单栏组件,元数据从最外层到 target vlaue 的路径上文案全部高亮 。所以需要找出经过 target vlaue 的路径有哪些?

需求

导航栏或者菜单栏组件,元数据从最外层到 target vlaue 的路径上文案全部高亮 。所以需要找出经过 target vlaue 的路径有哪些?

例子

元数据数据结果如下:

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

查找出该元数据所有的路径:

/**
 * 获取所有路径
 */
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
}

优化所有路径方法,找出指定 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
}

自测结果:


来自:https://segmentfault.com/a/1190000040339852


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_10529