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" }, ] } ]
逻辑说明
- 先将搜索字符串转成小写,仅转换一次以提升性能,同时避免大小写敏感问题;
- 用
array.filter()遍历父对象数组,保留满足条件的父对象; - 对每个父对象,通过
itemsList.some()判断:只要子数组里有任意一个项的name(转小写后)包含搜索字符串,就保留该父对象。
内容的提问来源于stack exchange,提问作者Owenn
相关产品推荐
相关产品推荐

