如何基于含多层嵌套子项的hierarchyList过滤topicsList数组?
多层嵌套结构下的数组过滤解决方案
问题说明
现有两个数组topicsList和hierarchyList,当前代码仅能根据hierarchyList顶层的topicId过滤topicsList,但hierarchyList存在多层嵌套的children结构(层级不固定)。需要实现过滤掉所有在hierarchyList(含各级子项)中存在对应topicId的topicsList元素,预期输出仅保留topicId为7的项。
原代码问题分析
原代码通过map方法只提取了hierarchyList顶层元素的topicId存入Set集合,没有遍历处理嵌套的children节点,导致子节点的topicId(如6、10)未被纳入过滤范围,最终过滤结果不符合预期。
修改后的代码实现
let topicsList = [{ "topicId": 1, "topicName": "Introduction", }, { "topicId": 2, "topicName": "How to Guide", }, { "topicId": 3, "topicName": "Support", }, { "topicId": 6, "topicName": "Lamborghini", }, { "topicId": 7, "topicName": "Mercedes Benz", }, { "topicId": 10, "topicName": "Skoda", } ] let hierarchyList = [{ "topicId": 1, "topicName": "Introduction", }, { "topicId": 2, "topicName": "How to Guide", "children": [{ "topicId": 6, "topicName": "Lamborghini", "children": [{ "topicId": 10, "topicName": "Skoda", }] }] }, { "topicId": 3, "topicName": "Support" } ] // 递归遍历所有层级,收集所有topicId function collectTopicIds(nodes) { const ids = new Set(); const traverse = (node) => { ids.add(node.topicId); // 存在子节点则继续遍历 if (node.children?.length) { node.children.forEach(traverse); } } nodes.forEach(traverse); return ids; } const topicIds = collectTopicIds(hierarchyList); // 过滤掉所有在hierarchyList中存在的topicId topicsList = topicsList.filter(({ topicId }) => !topicIds.has(topicId)); console.log(topicsList);
执行结果
运行代码后,控制台输出符合预期:
[{"topicId": 7, "topicName": "Mercedes Benz"}]
内容的提问来源于stack exchange,提问作者Mitul Panchal
相关产品推荐
相关产品推荐

