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

JavaScript按StatusId过滤对象并合并统计CSR数量问题

按StatusId过滤并统计数据格式修正

需求说明

  • 按StatusId过滤对象,统计每个StatusName对应的总数据量(all字段)及各CSR_Name的出现次数
  • 当前使用forEach方法实现后得到嵌套数组输出,需修正JavaScript代码以达成目标输出

输入数据

[
    {
        "StatusId": 2,
        "StatusName": "ordered",
        "CSR_NameId": 2,
        "CSR_Name": "test"
    },
    {
        "StatusId": 3,
        "StatusName": "delivered",
        "CSR_NameId": 3,
        "CSR_Name": "test2"
    },
    {
        "StatusId": 5,
        "StatusName": "created",
        "CSR_NameId": 2,
        "CSR_Name": "test"
    },
    {
        "StatusId": 27,
        "StatusName": "quoted",
        "CSR_NameId": 2,
        "CSR_Name": "test"
    }
]

期望输出

[
    {
        "ordered": {
            "all": 2,
            "test": 1,
            "test2": 1
        },
        "delivered": {
            "all": 3,
            "test": 2,
            "test2": 1
        },
        "created": {
            "all": 2,
            "test": 2
        },
        "quoted": {
            "all": 1,
            "test": 1
        }
    }
]

当前尝试代码

// get unique ID
datas.forEach(i => !uniq.includes(i.StatusId) ? uniq.push(i.StatusId) : '' );
// filter by ID
uniq.forEach(id => {
    res.push(datas.filter(o => o.StatusId === id));
})

当前输出

[
    [
        { StatusId: 2, StatusName: 'ordered', CSR_NameId: 2, "CSR_Name": "test"},
        { StatusId: 2, StatusName: 'ordered', CSR_NameId: 3, "CSR_Name": "test2" }
    ],
    [
        { StatusId: 3, StatusName: 'delivered', CSR_NameId: 3, "CSR_Name": "test2" },
        { StatusId: 3, StatusName: 'delivered', CSR_NameId: 2, "CSR_Name": "test" },
        { StatusId: 3, StatusName: 'delivered', CSR_NameId: 2, "CSR_Name": "test" }
    ],
    [
        { StatusId: 5, StatusName: 'created', CSR_NameId: 2, "CSR_Name": "test" },
        { StatusId: 5, StatusName: 'created', CSR_NameId: 2, "CSR_Name": "test" }
    ],
    [
        { StatusId: 27, StatusName: 'quoted', CSR_NameId: 2, "CSR_Name": "test" }
    ]
]

修正后的代码

const datas = [/* 你的输入数据 */];
const resultObj = {};

datas.forEach(item => {
    const statusName = item.StatusName;
    // 初始化当前StatusName的统计结构
    if (!resultObj[statusName]) {
        resultObj[statusName] = { all: 0 };
    }
    // 总数据量计数+1
    resultObj[statusName].all++;
    // 对应CSR_Name计数+1,未统计过则初始化为1
    const csrName = item.CSR_Name;
    resultObj[statusName][csrName] = (resultObj[statusName][csrName] || 0) + 1;
});

// 包装成数组,匹配期望输出格式
const finalResult = [resultObj];
console.log(finalResult);

代码说明

  1. 无需提前提取唯一ID再过滤,直接遍历输入数据,用resultObj按StatusName分组统计
  2. 对每个数据项:
    • 检查当前StatusName的统计结构是否存在,不存在则初始化包含all字段的对象
    • 递增all字段的总计数
    • 递增对应CSR_Name的计数,若该名称未统计过则设为1
  3. 最后将统计好的对象放入数组,完全匹配期望的输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:13:11