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

JavaScript嵌套数组过滤:根据子对象name筛选父元素

嵌套数组筛选:保留子数组含指定属性值的父对象

要实现嵌套数组的筛选,只需修改原函数的判断逻辑——不再直接检查当前对象的name,而是遍历父对象的itemsList子数组,判断是否存在至少一个子项的name包含目标字符串(忽略大小写)。

修改后的筛选函数

function filterParentByChildName(array: any[], searchStr: string) {
  const lowerSearch = searchStr.toLowerCase();
  return array.filter(parentObj => 
    parentObj.itemsList.some(item => 
      String(item.name).toLowerCase().includes(lowerSearch)
    )
  );
}

用法示例

const arrayObj = [
    {
        id: 1,
        itemsList: [
            { name: "Paul" },
            { name: "Newman" },
        ],
    },
    {
        id: 2,
        itemsList: [
            { name: "Jack" },
            { name: "Man" },
        ],
    },
];

// 筛选子项name包含"ul"的父对象
const outputArray = filterParentByChildName(arrayObj, "ul");
console.log(outputArray);

输出结果

[
    {
        id: 1,
        itemsList: [
            { name: "Paul" },
            { name: "Newman" },
        ]
    }
]

逻辑说明

  1. 先将搜索字符串转成小写,仅转换一次以提升性能,同时避免大小写敏感问题;
  2. 用array.filter()遍历父对象数组,保留满足条件的父对象;
  3. 对每个父对象,通过itemsList.some()判断:只要子数组里有任意一个项的name(转小写后)包含搜索字符串,就保留该父对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:24:20