You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:将扁平JSON结构转换为层级结构的实现方案

解决扁平JSON转层级结构的问题

我来帮你搞定这个层级转换的难题!不管扁平数组里的条目顺序如何,我们都可以通过路径拆分+逐层构建的方式实现需求。

核心思路

  1. 拆分路径:把每个Key按/分割成路径段,同时去掉目录节点末尾的/(比如root/second-root/会拆成['root', 'second-root'])。
  2. 逐层构建层级:从根对象开始,沿着拆分后的路径一步步创建节点。如果某个父节点不存在,就先创建它并设置Value: null(因为是目录节点)。
  3. 赋值最终节点:每个条目的最后一个路径段对应最终节点,直接设置它的Value属性。

实现代码

function splitKey(key) {
  // 移除末尾的斜杠,再按斜杠分割成路径段
  return key.replace(/\/$/, '').split('/');
}

function convertToHierarchy(settings) {
  const root = {};
  
  settings.forEach(item => {
    const segments = splitKey(item.Key);
    let currentNode = root;
    
    // 遍历路径段,直到倒数第二个,创建中间的目录节点
    for (let i = 0; i < segments.length - 1; i++) {
      const segment = segments[i];
      if (!currentNode[segment]) {
        // 目录节点默认Value为null
        currentNode[segment] = { Value: null };
      }
      currentNode = currentNode[segment];
    }
    
    // 处理最后一个路径段,设置对应的值
    const lastSegment = segments[segments.length - 1];
    currentNode[lastSegment] = { Value: item.Value };
  });
  
  // 按照需求返回包含根对象的数组
  return [root];
}

// 测试你的示例数据
const setting = [
 { Key: 'root/', Value: null, },
 { Key: 'root/second-root/', Value: null, },
 { Key: 'root/second-root/names/', Value: null, },
 { Key: 'root/second-root/names/capital-letter', Value: true, },
 { Key: 'root/second-root/countries/', Value: null, },
 { Key: 'root/second-root/countries/enabledcountries', Value: 'US,UK,DK', },
 { Key: 'root/second-root/countries/async', Value: 'true', },
 { Key: 'root/second-root/countries/manual', Value: 'true', },
 { Key: 'root/second-root/countries/limit', Value: '4200', },
 { Key: 'root/second-root/names/onyl-last-name', Value: false, },
];

const wantedResult = convertToHierarchy(setting);
console.log(JSON.stringify(wantedResult, null, 2));

代码说明

  • splitKey函数:专门处理路径字符串,确保目录节点的路径段不带末尾的斜杠,保证拆分后的路径数组统一。
  • convertToHierarchy函数:
    • 初始化一个空的根对象,用来承载整个层级结构。
    • 遍历每个设置条目,沿着路径段逐层检查并创建节点:如果当前节点下没有对应的子节点,就创建一个带Value: null的目录节点。
    • 最后定位到当前条目的目标节点,赋值对应的Value。
  • 这个方法完全不依赖条目的顺序,不管先处理哪个路径,都能正确构建出完整的层级结构。

内容的提问来源于stack exchange,提问作者user3711421

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:47:51