需求场景 在element的级联面板中使用的数据树形菜单,通过isShow来判断是否勾选,我们知道级联面板的勾选情况的数据是[[1,2],[1,4,5]]这样的形式,但是后台传来的数据是整个树形结构的数据,通过isShow来判断是否勾选。我们需要把数据处理成我们可以使用的二维数组。
树状结构如下:
[
{
id: 1,
name: '1',
isShow: 1,
children: [
{
id: 2,
name: '2',
isShow: 1,
children: null
},
{
id: 3,
name: '3',
isShow: 0,
children: null
},
{
id: 4,
name: '4',
isShow: 1,
children: [
{
id: 5,
name: '5',
isShow: 1,
children: null
},
]
}
]
},
{
id: 6,
name: '6',
isShow: 0,
children: [
{
id: 7,
name: '7',
isShow: 0,
children: null
}
]
}
]
// 转成[[1,2],[1,4,5]]这样的形式
当我们只需要展示ishow为1的数据可以使用递归处理将所有isshow为1的数据过滤出来
function filterMenuList(list) {
const copyList = JSON.parse(JSON.stringify(list))
const filterList = list => {
if (list instanceof Array && list.length > 0) {
const temp = list.filter(item => item.isShow=== 1)
temp.forEach(e => {
if (e.children) {
e.children = filterList(e.children)
}
})
return temp
}
}
return filterList(copyList)
}
将数据根据要求转成二维数组
function treeToArray(list) {
const arr = []
let temp = []
const flatten = (list, arr) => {
list.forEach(item => {
if(item.ishow === 1) {
if (item.children === null || item.children.length === 0) {
arr.push(temp.concat([item.id]))
} else {
temp.push(item.id)
flatten(item.children, arr)
}
}
})
temp = []
return arr
}
flatten(list, arr)
return arr
}