首页 > 解决方案 > 如何构建 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}
    }
}

标签: javascriptarraysjson

解决方案


如果需要,您可以简单地迭代用于构建新嵌套结构的键。

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; }


推荐阅读