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

如何在JavaScript中按noOfResubmit值分组JSON对象并构建目标结构

按noOfResubmit字段分组JSON数组的实现方法

需求说明

给定如下JSON数组:

const ab = [
{"Round": 1, "noOfResubmit": 1, "row": 0, "date": "Nov 24 - 30", "week": "Tuesday - Monday"},
{"Round": 1, "noOfResubmit": 1, "row": 1, "date": "Nov 8 - 14", "week": "Sunday - Saturday"},
{"Round": 1, "noOfResubmit": 2, "row": 4, "date": "Sep 1 - 14", "week": "Tuesday - Monday"},
{"Round": 1, "noOfResubmit": 2, "row": 5, "date": "Jan 1 - 7", "week": "Thursday - Wednesday"}
]

需要将数组按noOfResubmit的唯一值(如1、2)分组,生成如下结构的对象:

const c ={
    "1": [{"Round": 1, "noOfResubmit": 1, "row": 0, "date": "Nov 24 - 30", "week": "Tuesday - Monday"}, {"Round": 1, "noOfResubmit": 1, "row": 1, "date": "Nov 8 - 14", "week": "Sunday - Saturday"}],
    "2": [{"Round": 1, "noOfResubmit": 2, "row": 4, "date": "Sep 1 - 14", "week": "Tuesday - Monday"},{"Round": 1, "noOfResubmit": 2, "row": 5, "date": "Jan 1 - 7", "week": "Thursday - Wednesday"}]
}

实现方法

方法1:使用Array.prototype.reduce(简洁高效)

reduce方法可以直接遍历数组并累积结果,是处理分组需求的常用方式:

const c = ab.reduce((acc, curr) => {
  // 以noOfResubmit的值作为键,转为字符串保证键的一致性
  const key = curr.noOfResubmit.toString();
  // 如果当前键不存在,初始化一个空数组
  if (!acc[key]) {
    acc[key] = [];
  }
  // 将当前对象推入对应分组的数组
  acc[key].push(curr);
  return acc;
}, {}); // 初始值为空对象

方法2:使用for...of循环(直观易懂)

如果觉得reduce逻辑不够直观,可以用普通循环实现:

const c = {};
for (const item of ab) {
  const key = item.noOfResubmit.toString();
  // 检查分组是否存在,不存在则创建
  if (!c[key]) {
    c[key] = [];
  }
  c[key].push(item);
}

两种方法最终都会生成符合预期的分组对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:02:24