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

如何将JSON对象数组拆分为每组3个元素的块数组?

如何将JSON对象数组拆分为固定大小的块数组

你遇到的这个数组分块需求很常见,其实你用reduce实现的核心逻辑完全没问题——这个方法不管处理普通字符串数组还是对象数组,逻辑都是通用的。你觉得它对对象数组无效,大概率是代码细节没调整对(比如分块大小设成了2而非你需要的3,或者变量声明的语法问题)。

修正后的可行代码

针对你的示例输入,我们把分块大小设为3,同时调整代码的语法规范,就能得到你想要的结果:

const perChunk = 3; // 每组要包含的元素数量
const inputArray = [
  { title: "asd", description: "asd" },
  { title: "asz", description: "sd" },
  { title: "ws", description: "sd" },
  { title: "re", description: "sd" },
  { title: "32", description: "xxs" },
  { title: "xxc", description: "11" }
];

const chunkedArray = inputArray.reduce((resultArray, item, index) => {
  const chunkIndex = Math.floor(index / perChunk);
  // 如果当前索引对应的块不存在,创建一个新空数组
  if (!resultArray[chunkIndex]) {
    resultArray[chunkIndex] = [];
  }
  // 将当前元素推入对应块中
  resultArray[chunkIndex].push(item);
  return resultArray;
}, []);

console.log(chunkedArray);

代码运行结果

这段代码会输出你期望的块数组:

[
  [
    { title: "asd", description: "asd" },
    { title: "asz", description: "sd" },
    { title: "ws", description: "sd" }
  ],
  [
    { title: "re", description: "sd" },
    { title: "32", description: "xxs" },
    { title: "xxc", description: "11" }
  ]
]

为什么你的原代码对对象数组"无效"?

你的原代码里perChunk设为了2,而且变量声明没有用const/let(在严格模式下会报错),但核心逻辑是没问题的。只要把分块大小改成你需要的3,并且修正变量声明的语法,就能完美处理对象数组——因为reduce只关心数组的元素位置,不管元素是字符串还是对象,都会按照索引正确分块。

另一种可选实现(slice方法)

如果你觉得reduce的写法有点绕,也可以用Array.from配合slice来实现,代码更直观:

const perChunk = 3;
const inputArray = [/* 你的对象数组 */];

const chunkedArray = Array.from({ length: Math.ceil(inputArray.length / perChunk) }, (_, i) => {
  return inputArray.slice(i * perChunk, (i + 1) * perChunk);
});

这个方法先计算需要的总块数,然后每一块用slice截取原数组的对应片段,同样能得到你想要的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:10:32