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

JavaScript使用reduce处理对象数组报错,求属性过滤功能正确实现

问题原因

你的代码存在3处核心错误:

  1. reduce的第一个参数要求传入迭代回调函数,你直接执行了filterProperties(propNames, objs),返回结果是对象而非函数,因此触发<Object> not a function报错
  2. 没有为reduce指定初始累积值,你需要输出数组,初始值必须设为空数组[]
  3. 函数没有添加return语句,执行后会返回undefined
正确实现(reduce版本)
function filterPropertiesN(propNames, objs) {
    // 第一个参数为迭代回调,第二个参数为初始空累积数组
    return objs.reduce((acc, currentObj) => {
        // 对当前遍历到的单个对象做属性筛选,推入累积数组
        acc.push(filterProperties(propNames, currentObj));
        // 返回累积数组供下一轮迭代使用
        return acc;
    }, []);
}
补充说明

当前需求是一对一转换数组元素,没有强制要求用reduce的话,用map实现更简洁:

function filterPropertiesN(propNames, objs) {
    return objs.map(obj => filterProperties(propNames, obj));
}

内容的提问来源于stack exchange,提问作者Mário Friande

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:36:04