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

如何合并JS数组中同route键的对象并新增calls数组?

合并对象数组中相同route的条目,提取query和time到calls数组

可以用Array.prototype.reduce()高效实现这个转换逻辑,代码如下:

const originalArray = [
    { query: "query1", route: "home", time: 1234 },
    { query: "query2", route: "dashboard", time: 4324 },
    { query: "query3", route: "home", time: 1200 },
    { query: "query4", route: "admin", time: 3333 },
    { query: "query5", route: "admin", time: 5435 },
];

const mergedArray = Object.values(
    originalArray.reduce((acc, item) => {
        // 如果当前route还没被分组,初始化结构
        if (!acc[item.route]) {
            acc[item.route] = {
                route: item.route,
                calls: []
            };
        }
        // 提取query和time存入对应route的calls数组
        acc[item.route].calls.push({
            query: item.query,
            time: item.time
        });
        return acc;
    }, {})
);

console.log(mergedArray);

步骤说明:

  1. 用reduce遍历原始数组,构建一个以route为键的临时对象,每个键对应目标结构的雏形(包含route和空calls数组)
  2. 每处理一个条目时,判断当前route是否已存在于临时对象中,不存在则初始化
  3. 把当前条目的query和time字段单独提取出来,push到对应route的calls数组里
  4. 最后用Object.values()把临时对象的所有值提取出来,转换成你需要的数组格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:20:22