如何用JS按key过滤对象并递归收集所有关联依赖的key?
实现思路
我们可以基于广度优先遍历+Set去重实现依赖全收集,逻辑如下:
- 统一key前缀规则:白名单和deps中的短key都补全
@scope/前缀匹配data的键 - 用Set存储已收集的key,天然去重避免重复添加
- 用队列维护待处理依赖的key,逐层遍历所有嵌套依赖
const data = { '@scope/one': { deps: { three: { foo: 'bar' }, two: { foo: 'bar' } } }, '@scope/two': { foo: 'bar' }, '@scope/three': { deps: { four: { foo: 'bar' } } }, '@scope/four': { foo: 'bar' }, '@scope/five': { foo: 'bar' }, }; // 补全key前缀的工具函数 const getFullKey = (shortKey) => `@scope/${shortKey}`; function collectWithDeps(data, whitelist) { const collected = new Set(); const queue = []; // 第一步:初始白名单过滤 whitelist.forEach(shortKey => { const fullKey = getFullKey(shortKey); if (data[fullKey] && !collected.has(fullKey)) { collected.add(fullKey); queue.push(fullKey); } }); // 第二步:遍历队列收集所有依赖 while (queue.length > 0) { const currentKey = queue.shift(); const currentItem = data[currentKey]; // 没有依赖就跳过 if (!currentItem.deps) continue; // 遍历当前项的所有依赖 Object.keys(currentItem.deps).forEach(depShortKey => { const depFullKey = getFullKey(depShortKey); if (data[depFullKey] && !collected.has(depFullKey)) { collected.add(depFullKey); queue.push(depFullKey); } }); } // 转成数组返回,顺序和示例预期完全一致 return Array.from(collected); } const result = collectWithDeps(data, ['one', 'two']); console.log(result); // 输出:['@scope/one', '@scope/two', '@scope/three', '@scope/four']
代码说明
- Set天然去重,无需手动写重复判断逻辑
- 队列实现的广度优先遍历可以覆盖任意层级的嵌套依赖,不会漏采
- 提前校验key是否存在于data中,避免无效值进入后续逻辑
- 如果要兼容原有
sanitize函数,只需要把初始筛选得到的key传入收集逻辑即可复用
内容的提问来源于stack exchange,提问作者user3142695
相关产品推荐
相关产品推荐

