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

更新日期: 2021-07-13 阅读: 1.8k 标签: 数组

需求

导航栏或者菜单栏组件,元数据从最外层到 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://fly63.com/article/detial/10529

相关推荐

indexOf的三种使用方法

indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。这里基本用法大家一般都清楚,一般在实际工作中常与数组的方法合用来对数组进行一些操作

关于Vue不能监听(watch)数组变化

vue无法监听数组变化的情况,但是数组在下面两种情况下无法监听:利用索引直接设置数组项时,例如arr[indexofitem]=newValue;修改数组的长度时,例如arr.length=newLength

JS计算两个数组的交集、差集、并集、补集(多种实现方式)

使用 ES5 语法来实现虽然会麻烦些,但兼容性最好,不用考虑浏览器 JavaScript 版本,使用 ES5 语法来实现虽然会麻烦些,但兼容性最好,不用考虑浏览器 JavaScript 版本。也不用引入其他第三方库。

js数组中改变元素的位置:互换,置顶,上移,下移

unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度。shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。splice() 方法可删除从 index 处开始的零个或多个元素

js使用数组+循环+条件实现数字转换为汉字的简单方法。

单个数字转汉字的解决方法:利用数组存储0-9的汉字、 ary.length和str.length不用多说,这是指ary数组和str字符串的长度。这里我们需要注意的是str.charAt(j)和ary[i],分别指在str这个字符串中索引为j的元素,在ary中索引为i的元素。

Js遍历数组时注意 Empty Item 的影响

这两天碰到个问题:从日志中发现一些来自 iOS 10.3 的报错「Cannot read property \\\'xxx\\\' of undefined」,定位到代码的报错位置,发现是遍历某数组时产生的报错,该数组的元素应该全都是 Object,但实际上出现了异常的元素

JS数组扁平化(flat)方法总结

需求:多维数组=>一维数组 ;flat和flatMap方法为ES2019(ES10)方法,目前还未在所有浏览器完全兼容。第四种处理:用 reduce 实现数组的 flat 方法

数组、字符串去重

今天说的数组和字符串去重呢,主要用到es6新的数据结构 Set,它类似于数组,但是成员的值都是唯一的,没有重复的值,所以活用Set来进行数组和字符串的去重。

Js数组中所有方法(超详细)

concat()把元素衔接到数组中。 every() 方法使用指定函数检测数组中的所有元素:filter()返回满足断言函数的数组元素。forEach()为数组的每一个元素调用指定函数。

[译]async-await 数组循环的几个坑

在 Javascript 循环中使用 async/ await 循环遍历数组似乎很简单,但是在将两者结合使用时需要注意一些非直观的行为。让我们看看三个不同的例子,看看你应该注意什么,以及哪个循环最适合特定用例。

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!