通过某个字段状态为true,来控制显示,返回a为true的对象组成的数组

根据树结构中某个字段的true/false关系,筛选出为true的树

let arr = [
        {
            a: true,
            child: [
                {
                    a: true,
                    b: 2
                },
                {
                    a: false,
                    b: 3
                }
            ]
        },
        {
            a: true,
            child: [
                {
                    a: true,
                    b: 2,
                    child: [
                        {
                            a: true,
                            b: 4
                        },
                        {
                            a: false,
                            b: 4
                        }
                    ]
                },
                {
                    a: true,
                    b: 3
                }
            ]
        },
        {
            a: false,
            child: [
                {
                    a: false,
                    b: 2
                },
                {
                    a: false,
                    b: 3
                }
            ]
        }
    ]

    //通过某个字段状态为true,来控制显示
    //返回a为true的对象组成的数组
    const filterMenu = menuList => {
	return menuList.filter(item => {
		return item.a == true;
	}).map(item => {
		item = Object.assign({}, item)
		if(item.child && item.child.length > 0) {
			item.child = filterMenu(item.child)
		}
		return item
	})
}
// 调用
let menuList = filterMenu(arr);
console.log(menuList)

  

原文地址:https://www.cnblogs.com/agen-su/p/14439707.html