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

如何同时过滤对象数组中的header属性与content内容?

同时过滤对象数组的header与content内容解决方案

需求说明

需要对给定的对象数组实现双重过滤逻辑:

  • 保留满足以下任一条件的对象:
    1. 对象的header包含指定关键词
    2. 对象的content数组中存在name或username属性包含指定关键词的项
  • 保留的对象需按规则处理content:
    • 若header匹配关键词,保留完整的content数组
    • 若仅content中有匹配项,则只保留content中符合条件的项

原始数据结构:

const testData = [
    {
        header: '公众号',
        content: [{ name: '系統公告'}],
    },
    {
        header: '我的群聊',
        content: [{ name: 'test01'}, { name: '下'}, { name: '公级用户'}],
    },
    {
        header: '上级用户',
        content: [{ username: 'root' }],
    },
    {
        header: '下级用户',
        content: [{ name: 'test0301'}, { name: '1234'},],
    },
];

预期效果

  • 输入关键词"下",输出结果:
[
    {
        header: '我的群聊',
        content: [{ name: '下'}],
    },
    {
        header: '下级用户',
        content: [{ name: 'test0301'}, { name: '1234'},],
    },
]
  • 输入关键词"我",输出结果:
[
    {
        header: '我的群聊',
        content: [{ name: 'test01'}, { name: '下'}, { name: '公级用户'}],
    },
]

解决方案代码

function filterData(data, keyword) {
    return data.map(item => {
        const newItem = {...item};
        const isHeaderMatch = newItem.header.includes(keyword);
        const matchedContent = newItem.content.filter(contentItem => {
            return contentItem.name?.includes(keyword) || contentItem.username?.includes(keyword);
        });

        if (isHeaderMatch) {
            return newItem;
        } else if (matchedContent.length > 0) {
            newItem.content = matchedContent;
            return newItem;
        }
        return null;
    }).filter(Boolean);
}

// 测试示例
console.log(filterData(testData, "下"));
console.log(filterData(testData, "我"));

代码解释

  1. 遍历处理每个对象:用map遍历数组,对每个对象做匹配判断和内容处理
  2. 避免修改原数据:通过对象展开运算符{...item}拷贝原对象
  3. 匹配逻辑:
    • 先检查header是否包含关键词
    • 再过滤content中name或username包含关键词的项
  4. 结果处理:
    • 若header匹配,直接返回拷贝后的对象
    • 若仅content有匹配项,替换content为过滤后的数组再返回
    • 无匹配项则返回null,最后用filter(Boolean)移除这些无效对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 08:54:22