javascript - 如何构建 JSON 并同时遍历它?
问题描述
我有一个名为pathlist
. 我们的假设是数组及其子数组的长度接近无穷大。
let pathlist = [
[ 'en', 'family-law' ],
[ 'en', 'family-law', 'marriage' ],
[ 'en', 'family-law', 'divorce' ],
[ 'en', 'family-law', 'religious-divorce' ],
[ 'en', 'human-rights-law' ],
[ 'en', 'refugee-law' ]
...
]
我想遍历这个列表并构建一个 JSON。在此示例中,它看起来像这样。有没有人可以建议的方法?
navigator = {
'en': {
'family-law': {
'marriage': {},
'divorce': {},
'religious-divorce': {}
},
'human-rights-law': {},
'refugee-law': {},
...
}
}
这是我令人遗憾的语无伦次的回答。
let navigator = {}
let stem
for(let path of pathlist){
for(let pathitem of path){
stem = navigator
if(stem[pathitem]){
stem = stem[pathitem]
} else {
stem[pathitem] = {}
}
navigator = {...navigator, stem}
}
}
解决方案
如果需要,您可以简单地迭代用于构建新嵌套结构的键。
const
setStructure = (target, keys) => (keys.reduce((o, k) => o[k] ??= {}, target), target),
pathlist = [['en', 'family-law'], ['en', 'family-law', 'marriage'], ['en', 'family-law', 'divorce'], ['en', 'family-law', 'religious-divorce'], ['en', 'human-rights-law'], ['en', 'refugee-law']],
result = pathlist.reduce(setStructure, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- outlook - Outlook Web 插件 - 更改标题栏的颜色
- javascript - 通过倒计时使图像居中并在页面内响应
- svg - 谷歌工作表脚本导出图表为矢量图像 (svg/eps)
- python - 在 PyInstaller 应用程序中启用 Windows 长文件路径支持
- java - 在命令行的 Kotlin Jar 文件中包含文件和目录
- python - 如何使用 django 泛型类删除我的帖子?
- amazon-web-services - 使用 Aurora Serverless Data API 时传递 IAM 凭证?
- sql - 为什么使用索引不会影响我的查询长度?
- ssis - 返回状态值 4 和状态文本“文本被截断或一个或多个字符在目标代码页中不匹配
- python - Python Webscraping:需要帮助从 span html 标记获取数据值