demand
Navigation bar or menu bar component, the path of metadata from the outermost layer to target vlaue is all highlighted above. So you need to find out what paths go through the target vlaue?
example
- The metadata data results are as follows:
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,
},
],
}
]
}
]
- Find out all the paths of the metadata:
/**
* 获取所有路径
*/
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
}
- Optimize all path methods to find the path with the specified 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
}
- Self-test results:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。