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
相关产品推荐
相关产品推荐

