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

如何将JavaScript数组转换为元素逐层嵌套的对象结构?

数组转链式嵌套对象实现

需求说明

给定JavaScript数组 ['banana', 'apple', 'grape'],转换规则为:数组每个元素值均作为对象属性,且后一个元素为前一个元素对应对象的子属性,最终输出如下结构:

{
   banana: {
       apple: {
           grape: { }
       }
   }
}

实现方法

方法1:reduceRight 最简实现

利用数组的reduceRight方法从右向左遍历,逐层包裹生成嵌套对象,代码最简洁:

const arr = ['banana', 'apple', 'grape'];
const nestedObj = arr.reduceRight((innerObj, currentKey) => {
  return { [currentKey]: innerObj }
}, {});

实现逻辑:

  • 初始传入累加器的值为空对象{},对应最内层grape对应的空对象
  • 遍历到grape时,返回{ grape: {} }作为下一轮遍历的累加值
  • 遍历到apple时,返回{ apple: { grape: {} } }
  • 遍历到最外层banana时,即可得到目标嵌套结构

方法2:倒序循环实现

逻辑和reduceRight完全一致,不依赖高阶函数,兼容性更好:

const arr = ['banana', 'apple', 'grape'];
let nestedObj = {};
for (let i = arr.length - 1; i >= 0; i--) {
  nestedObj = { [arr[i]]: nestedObj };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 11:06:33