javascript - 从数组创建对象,使用递归/减少?
问题描述
我对递归函数有点糟糕。
我想把这个...
const input = { regions: ["US", "CA", "LA"], checked: true };
...进入以下,使用递归和reduce
:
const output = {
US: {
CA: {
LA: true
}
}
};
帮助?我尝试了很多东西,但我的实验太尴尬了,无法分享。
解决方案
使用 迭代区域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);
推荐阅读
- javascript - 在 drawImage IOS Safari 上使用视频元素的替代方法
- django - Django - 通过多对多上最近的表行加入
- hyperlink - RTF 中的内部超链接
- c++ - 为什么那里不调用普通函数?
- javascript - 在 passport.authenticate successRedirect 中使用条件
- shopify - 在页面模板中创建的 Shopify/liquid 代码段未在产品模板中正确加载
- keyboard-shortcuts - 是否有加速器关键解决方案来赋予 TrackBar 焦点
- apache-kafka - 如何在 Windows 中设置 Kafka 属性(在哪些属性文件中)并监控 Kafka 集群运行状况?
- javascript - JS按特定属性映射对象数组
- python - 如何使python进程访问所有内存?