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

如何使用filter()和find()从嵌套数组筛选出爱好为reading的对象?

解决方法:筛选爱好包含reading的用户对象

你可以结合Array.filter()和Array.some()(或Array.find())来实现需求,核心是在筛选外层用户对象时,检查其内部的hobbies数组是否存在目标爱好。

代码实现

// 原始数据
const users = [
    {
        "id": 1,
        "name": "john",
        "hobbies": [
            {
                "id": 1,
                "name": "playing"
            }
        ]
    },
    {
        "id": 3,
        "name": "peter",
        "hobbies": [
            {
                "id": 3,
                "name": "reading"
            }
        ]
    }
];

// 筛选爱好包含reading的用户
const result = users.filter(user => {
    // 检查当前用户的hobbies数组中是否有name为reading的项
    return user.hobbies.some(hobby => hobby.name === 'reading');
});

console.log(result);

代码说明

  • filter():遍历外层的用户数组,只保留满足判断条件的用户对象
  • some():遍历当前用户的hobbies数组,只要找到一个name为"reading"的爱好,就返回true,让该用户通过筛选

你也可以用find()替代some(),逻辑类似:

const result = users.filter(user => {
    return user.hobbies.find(hobby => hobby.name === 'reading') !== undefined;
});

如果觉得写法繁琐,还可以简化——因为find()找到目标会返回该对象(属于真值),找不到返回undefined(假值),所以直接把find()的结果作为判断条件即可:

const result = users.filter(user => user.hobbies.find(h => h.name === 'reading'));

内容的提问来源于stack exchange,提问作者user3804010

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 08:30:43