如何在嵌套数组对象结构中搜索含指定字符的元素?
数组筛选逻辑实现
原始数组结构
const originalArray = [ { key: "001", value: [{ Id: "2345", Name: "Test" }] }, { key: "112", value: [{ Id: "1234", Name: "UHV" }, { Id: "3424", Name: "ABC" }] }, { key: "222", value: [{ Id: "2312", Name: "ABD" }, { Id: "1321", Name: "RFV" }, { Id: "4567", Name: "ERF" }] } ];
需求说明
当搜索字符AB时,筛选出满足以下条件的元素:
- 父元素的
value数组中存在子项的Name包含AB - 仅保留父元素中符合条件的子项,剔除不符合的子项
实现代码
const searchKeyword = 'AB'; const filteredResult = originalArray .map(item => { // 筛选当前项value中Name包含搜索关键词的子元素 const matchedSubItems = item.value.filter(subItem => subItem.Name.includes(searchKeyword)); // 有匹配结果则返回更新后的对象,否则返回null return matchedSubItems.length ? { ...item, value: matchedSubItems } : null; }) // 过滤掉无匹配结果的父元素 .filter(item => item !== null); console.log(filteredResult);
输出结果
[ { key: "112", value: [{ Id: "3424", Name: "ABC" }] }, { key: "222", value: [{ Id: "2312", Name: "ABD" }] } ]
内容的提问来源于stack exchange,提问作者Gajini
相关产品推荐
相关产品推荐

