JS树形多级数据过滤,根据指定对象保存并保留数据格式

function filterTreeData(data, value) {
return data.filter(item = >{
if (item.value === value) {
return true;
}
if (item.children) {
item.children = filterTreeData(item.children, value);
return item.children.length > 0;
}
return false;
});
}

使用示例:

const treeData = [{
    label: 'Parent 1',
    value: 1,
    children: [{
        label: 'Child 1',
        value: 2,
        children: [{
            label: 'Grandchild 1',
            value: 3,
        },
        {
            label: 'Grandchild 2',
            value: 4,
        },
        ],
    },
    {
        label: 'Child 2',
        value: 5,
    },
    ],
},
{
    label: 'Parent 2',
    value: 6,
    children: [{
        label: 'Child 3',
        value: 7,
    },
    ],
},
];

const filteredData = filterTreeData(treeData, 4);
console.log(filteredData);
[{
    label: 'Parent 1',
    value: 1,
    children: [{
        label: 'Child 1',
        value: 2,
        children: [{
            label: 'Grandchild 2',
            value: 4,
        },
        ],
    },
    ],
},
]

 

posted @ 2023-04-18 20:27  三寸日光  阅读(545)  评论(0编辑  收藏  举报