首页 > 解决方案 > 从数组创建对象,使用递归/减少?

问题描述

我对递归函数有点糟糕。

我想把这个...

const input = { regions: ["US", "CA", "LA"], checked: true };

...进入以下,使用递归和reduce

const output = {
  US: {
    CA: {
      LA: true
    }
  }
};

帮助?我尝试了很多东西,但我的实验太尴尬了,无法分享。

标签: javascriptrecursion

解决方案


使用 迭代区域reduceRight,使用属性的初始值创建嵌套对象checked,并在每次迭代时用新对象(新累加器)包围它:

const input = { regions: ["US", "CA", "LA"], checked: true };
const { regions, checked } = input;

const output = regions.reduceRight((a, prop) => ({ [prop]: a }), checked);
console.log(output);


推荐阅读