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

如何使用字符串数组筛选包含嵌套结构的对象数组

实现嵌套对象的多条件筛选需求

给定产品数组和筛选条件数组,需筛选出同时满足所有筛选条件字符串匹配的对象,匹配逻辑要支持任意值类型(包括嵌套对象中的值)。

原始数据与筛选条件

产品数组

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']; 

实现思路

  1. 写一个递归函数,遍历对象的所有值(包括嵌套对象),将值转为字符串后检查是否包含目标筛选条件。
  2. 对每个产品,验证所有筛选条件是否都能在该产品的任意层级值中找到匹配。
  3. 用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:25:51