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

JavaScript多维数组按相同键合并值转换为嵌套对象的问题

问题原因

你的代码在处理同一年份的多个条目时,每次都直接给obj[年份]赋值一个全新的对象,之前同一年份下已经写入的属性会被完全覆盖,所以最终只会保留同一年份最后一条数据的内容。

修正方案

1. 基础for循环版本(和你原有写法逻辑最接近)

let obj = {}
for (let i = 0; i < array.length; i++) {
  const id = array[i][0];
  const year = array[i][1];
  const value = array[i][2];
  // 同一年份的对象不存在时先初始化为空对象
  if (!obj[year]) {
    obj[year] = {}
  }
  // 仅追加属性,不替换整个年份对象
  obj[year][id] = value.toString()
}

2. 更简洁的reduce写法(JS中数组分组转对象的常用方案)

const obj = array.reduce((result, item) => {
  const [id, year, value] = item
  // 初始化年份对应的空对象
  result[year] = result[year] || {}
  result[year][id] = value.toString()
  return result
}, {})

运行结果

两种写法最终得到的结构如下(你给出的预期结果中2014-15下存在两个重复的2键属于笔误,对象键不可重复,正确结果如下):

{
  "2013-14": { "1": "1234", "2": "2345" },
  "2014-15": { "1": "5234", "2": "7345" }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:15:03