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

JS过滤对象数组报employee.includes is not a function错误如何解决

错误原因

includes()是仅字符串、数组类型支持的方法,你遍历得到的employee是普通对象,不存在该方法,因此触发类型错误。同时你需要额外处理area为null的边界情况,否则直接访问area.name会抛出 Cannot read properties of null 报错。

正确实现代码

fetch(baseURL + "/employees")
.then(response => response.json())
.then(result => {
    // 可选链语法自动处理空值场景
    let vibeEmployees = result.filter(employee => employee?.area?.name === "Vibestuen");
    console.log(vibeEmployees)
})

如果运行环境不支持ES2020可选链,可以使用传统判空写法兼容:

fetch(baseURL + "/employees")
.then(response => response.json())
.then(result => {
    let vibeEmployees = result.filter(employee => {
        return employee.area !== null && employee.area.name === "Vibestuen";
    });
    console.log(vibeEmployees)
})

运行后得到的vibeEmployees就是所有area下name为Vibestuen的对象,对应你给出的示例数据会匹配到id为295、299的两条数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:15:06