如何将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
相关产品推荐
相关产品推荐

