如何通过js实现搜索菜单栏功能

菜单格式如下

[

{

"children": [],

"mText": "一级菜单1"

},

{

"children": [

{

"children": [],

"mText": "二级菜单1"

},

{

"children": [],

"mText": "二级菜单2"

}

],

"mText": "一级菜单2"

},

{

"children": [

{

"children": [

{

"children": [],

"mText": "三级菜单1"

},

{

"children": [],

"mText": "三级菜单2"

}

],

"mText": "二级菜单1"

},

{

"children": [

{

"children": [],

"mText": "三级菜单1"

}

],

"mText": "二级菜单2"

}

],

"mText": "一级菜单3"

}

]

搜索最下一级菜单名称,想得到他的父级、父级的父级、父级的父级的父级……,如搜索 三级菜单1得到如下的数据:
[

{

"children": [

{

"children": [

{

"children": [],

"mText": "三级菜单1"

}

],

"mText": "二级菜单1"

},

{

"children": [

{

"children": [],

"mText": "三级菜单1"

}

],

"mText": "二级菜单2"

}

],

"mText": "一级菜单3"

}

]


回答:

如何通过js实现搜索菜单栏功能
如何通过js实现搜索菜单栏功能

var list = [

{

"children": [],

"mText": "一级菜单1"

},

{

"children": [

{

"children": [],

"mText": "二级菜单1"

},

{

"children": [],

"mText": "二级菜单2"

}

],

"mText": "一级菜单2"

},

{

"children": [

{

"children": [

{

"children": [],

"mText": "三级菜单1"

},

{

"children": [],

"mText": "三级菜单2"

}

],

"mText": "二级菜单1"

},

{

"children": [

{

"children": [],

"mText": "三级菜单1"

}

],

"mText": "二级菜单2"

}

],

"mText": "一级菜单3"

}

]

let findTree = (list=[], keyword='')=> list.filter(item=> {

item.children = findTree(item.children, keyword);

return item.children.length || item.mText.includes(keyword);

});

findTree(list,'三级菜单2');

注意:要重新克隆一份数据,不然会修改原先的数据。
list = JSON.parse(JSON.stringify(list))

以上是 如何通过js实现搜索菜单栏功能 的全部内容, 来源链接: utcz.com/p/937052.html

回到顶部