如何使用字符串数组筛选包含嵌套结构的对象数组
实现嵌套对象的多条件筛选需求
给定产品数组和筛选条件数组,需筛选出同时满足所有筛选条件字符串匹配的对象,匹配逻辑要支持任意值类型(包括嵌套对象中的值)。
原始数据与筛选条件
产品数组
let products = [ { name: "A", color: "Blue", size: { size1: 1, size2: 2, size3: 3, }, }, { name: "B", color: "Blue", size: { size1: 5, size2: 19, size3: 22, }, }, { name: "C", color: "Black", size: 70 }, { name: "D", color: "Green", size: 50 }, ];
筛选条件
const filters = ['Blue','2'];
实现思路
- 写一个递归函数,遍历对象的所有值(包括嵌套对象),将值转为字符串后检查是否包含目标筛选条件。
- 对每个产品,验证所有筛选条件是否都能在该产品的任意层级值中找到匹配。
- 用
Array.filter()结合上述验证逻辑,得到最终筛选结果。
代码实现
// 递归检查对象是否包含目标字符串 const hasMatch = (obj, target) => { for (const value of Object.values(obj)) { if (typeof value === 'object' && value !== null) { // 嵌套对象递归检查 if (hasMatch(value, target)) return true; } else { // 非对象值转字符串后检查是否包含目标 if (String(value).includes(target)) return true; } } return false; }; // 执行筛选 const filteredProducts = products.filter(product => { // 确保所有筛选条件都匹配当前产品 return filters.every(filter => hasMatch(product, filter)); }); console.log(filteredProducts);
输出结果
[ { name: "A", color: "Blue", size: { size1: 1, size2: 2, size3: 3, }, } ]
内容的提问来源于stack exchange,提问作者kb9
相关产品推荐
相关产品推荐

