You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript嵌套对象过滤:根据关键字筛选生成新对象

实现JavaScript对象的关键字筛选功能

需求回顾

我们有一个多层嵌套的JavaScript对象,需要根据输入的关键字筛选出所有**键名包含该关键字(大小写不敏感)**的键值对,同时要注意:如果某一层的父对象在筛选后没有任何子项,就不要把这个空的父对象留在结果里。

原对象如下:

let x = { 
  "people" :{ "Sally": "value", "Bob" : "other value" }, 
  "cars" :{ "Saab" : "this", "Chevy": "that" }, 
  "trees":{ "Birch" : "what", "Oak" : "where" } 
}

预期效果:

  • 搜索 "S" → 返回只包含Sally和Saab的嵌套对象
  • 搜索 "b" → 返回包含Bob和Birch的嵌套对象
  • 搜索 "bo" → 只返回包含Bob的对象

实现方案

我写了一个递归函数来处理这个需求,它会遍历对象的每一层,筛选出符合条件的键,同时自动清理空的父对象:

function filterObjectByKey(obj, keyword) {
  // 把关键字转成小写,实现大小写不敏感匹配
  const lowerKeyword = keyword.toLowerCase();
  // 初始化结果对象
  const result = {};

  // 遍历当前对象的所有键
  for (const key of Object.keys(obj)) {
    const value = obj[key];
    // 如果当前值是对象,递归筛选
    if (typeof value === 'object' && value !== null) {
      const filteredChild = filterObjectByKey(value, keyword);
      // 如果递归后的子对象不为空,才加入结果
      if (Object.keys(filteredChild).length > 0) {
        result[key] = filteredChild;
      }
    } else {
      // 如果当前键名包含关键字(大小写不敏感),加入结果
      if (key.toLowerCase().includes(lowerKeyword)) {
        result[key] = value;
      }
    }
  }

  return result;
}

测试验证

我们来测试几个场景:

// 搜索"S"
console.log(filterObjectByKey(x, "S"));
// 输出:{ people: { Sally: 'value' }, cars: { Saab: 'this' } }

// 搜索"b"
console.log(filterObjectByKey(x, "b"));
// 输出:{ people: { Bob: 'other value' }, trees: { Birch: 'what' } }

// 搜索"bo"
console.log(filterObjectByKey(x, "bo"));
// 输出:{ people: { Bob: 'other value' } }

这个函数的优势在于:

  • 支持任意深度的嵌套对象(不仅仅是两层)
  • 自动过滤掉筛选后为空的父对象,避免结果里出现空对象
  • 大小写不敏感的匹配逻辑,完美契合需求示例

内容的提问来源于stack exchange,提问作者David Little

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:14:00