树状结构转二维数组

需求场景 在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
    }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值