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

JavaScript如何从二维数组动态生成对应层级的多维Object

二维数组转换为指定层级对象的实现方法

问题核心原因

出现二级属性覆盖是因为遍历过程中没有做前置存在性判断,每次都直接对一级/二级属性做全量赋值,导致已创建的属性被重置。

实现代码(forEach 版本,和你原先的实现思路对齐)

let array1 = [
  ['A', 'a1'],
  ['A', 'a1'],
  ['A', 'a2'],
  ['B', 'b1'],
  ['B', 'b1'],
  ['B', 'b2'],
];

const result = {};
array1.forEach(([firstLevelKey, secondLevelKey]) => {
  // 一级键不存在时才初始化,避免覆盖已有的一级对象
  if (!result[firstLevelKey]) {
    result[firstLevelKey] = {};
  }
  // 二级键不存在时才初始化,避免覆盖已有的二级对象,重复数据直接跳过
  if (!result[firstLevelKey][secondLevelKey]) {
    result[firstLevelKey][secondLevelKey] = {};
  }
});

console.log(result);
// 输出符合预期:{ A : {a1: {},a2:{}}, B: {b1:{},b2:{}}}

更简洁的 reduce 实现

也可以用数组reduce方法快速实现,逻辑和上面完全一致,语法更精简:

const result = array1.reduce((acc, [firstKey, secondKey]) => {
  acc[firstKey] ??= {};
  acc[firstKey][secondKey] ??= {};
  return acc;
}, {});

其中??=是空值合并赋值运算符,只有左侧值为undefined/null时才会执行赋值,等价于前面的if判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:06:00