如何同时过滤对象数组中的header属性与content内容?
同时过滤对象数组的header与content内容解决方案
需求说明
需要对给定的对象数组实现双重过滤逻辑:
- 保留满足以下任一条件的对象:
- 对象的
header包含指定关键词 - 对象的
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, "我"));
代码解释
- 遍历处理每个对象:用
map遍历数组,对每个对象做匹配判断和内容处理 - 避免修改原数据:通过对象展开运算符
{...item}拷贝原对象 - 匹配逻辑:
- 先检查
header是否包含关键词 - 再过滤
content中name或username包含关键词的项
- 先检查
- 结果处理:
- 若
header匹配,直接返回拷贝后的对象 - 若仅
content有匹配项,替换content为过滤后的数组再返回 - 无匹配项则返回
null,最后用filter(Boolean)移除这些无效对象
- 若
内容的提问来源于stack exchange,提问作者tommm2
相关产品推荐
相关产品推荐

