首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将数组转换为嵌套的JSON对象-角材料树

将数组转换为嵌套的JSON对象-角材料树
EN

Stack Overflow用户
提问于 2021-05-28 12:08:10
回答 2查看 1.2K关注 0票数 0

我正拼命地尝试以JSON嵌套格式从角树中获取选定的节点。到目前为止,我使用this.checklistSelection.selected成功地获得了选定的平面节点数组。但是我需要的是,我需要以JSON格式获得选定的节点,所有嵌套的JSON对象都按其级别排列。

代码语言:javascript
复制
[{item: "Risk Analysis", level: 0, expandable: true}
,{item: "Standard", level: 1, expandable: true}
,{item: "Active", level: 2, expandable: true}
,{item: "Volatility", level: 3, expandable: true}
,{item: "Contribution", level: 4, expandable: true}
,{item: "Total", level: 5, expandable: false}
,{item: "Systematic", level: 5, expandable: false}
,{item: "Specific", level: 5, expandable: false}
,{item: "VaR (95%, 2 weeks, Chebyshev)", level: 3, expandable: true}
,{item: "Contribution", level: 4, expandable: true}
,{item: "Total", level: 5, expandable: false}
,{item: "Systematic", level: 5, expandable: false}
,{item: "Specific", level: 5, expandable: false}
,{item: "Benchmark", level: 2, expandable: true}
,{item: "Volatility", level: 3, expandable: true}
,{item: "Contribution", level: 4, expandable: true}
,{item: "Total", level: 5, expandable: false}
,{item: "Systematic", level: 5, expandable: false}
,{item: "Specific", level: 5, expandable: false}
,{item: "VaR (95%, 2 weeks, Chebyshev)", level: 3, expandable: true}
,{item: "Contribution", level: 4, expandable: true}
,{item: "Total", level: 5, expandable: false}
,{item: "Systematic", level: 5, expandable: false}
,{item: "Specific", level: 5, expandable: false}
,{item: "Portfolio", level: 2, expandable: true}
,{item: "Volatility", level: 3, expandable: true}
,{item: "Contribution", level: 4, expandable: true}
,{item: "Total", level: 5, expandable: false}
,{item: "Systematic", level: 5, expandable: false}
,{item: "Specific", level: 5, expandable: false}
,{item: "VaR (95%, 2 weeks, Chebyshev)", level: 3, expandable: true}
,{item: "Contribution", level: 4, expandable: true}
,{item: "Total", level: 5, expandable: false}
,{item: "Systematic", level: 5, expandable: false}
,{item: "Specific", level: 5, expandable: false}]

预期:

代码语言:javascript
复制
"Risk Analysis": {
      "Standard": {
        "Active": {
          "Volatility": {
            "Contribution": ["Total", "Systematic", "Specific"]
          },
          "VaR (95%, 2 weeks, Chebyshev)": {
            "Contribution": ["Total", "Systematic", "Specific"]
          }
        },
        "Portfolio": {
          "Volatility": {
            "Contribution": ["Total", "Systematic", "Specific"]
          },
          "VaR (95%, 2 weeks, Chebyshev)": {
            "Contribution": ["Total", "Systematic", "Specific"]
          }
        },
        "Benchmark": {
          "Volatility": {
            "Contribution": ["Total", "Systematic", "Specific"]
          },
          "VaR (95%, 2 weeks, Chebyshev)": {
            "Contribution": ["Total", "Systematic", "Specific"]
          }
        }
      }
    }
  }

有人能指出,如果有一个方法,马特树提供的,或任何类型的功能,可以发挥这一魔力?

(预先谢谢:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-28 13:14:52

为了构建一棵树,您需要通过为每个项分配In来预处理数据。在分配关系时,可以使用堆栈来跟踪它们。

您可以分阶段完成此任务:

为每一项分配(applyRelationships)

  • Convert的idparentId键平面数组为树(listToTree)

  • Convert将树分配为对象(treeToObject)

在最初的例子中,我通过设置最大深度来强制每个对象嵌套.我没有使用expandable属性。在这个修改的例子中,我放弃了maxDepth参数。

代码语言:javascript
复制
const main = () => {
  useCases.forEach(({ data, expected }) => {
    const actual = buildTreeObject(data);
    console.log(JSON.stringify(actual) === JSON.stringify(expected));
    console.log(actual);
  });
};

const useCases = [{
  data: [
    { item: "Risk Analysis", level: 0, expandable: true },
    { item: "Volatility", level: 1, expandable: true },
    { item: "Total", level: 2, expandable: false },
    { item: "Systematic", level: 2, expandable: false },
    { item: "Specific", level: 2, expandable: false },
    { item: "TaR (68%, 1 year)", level: 1, expandable: true },
    { item: "Total", level: 2, expandable: false },
    { item: "Systematic", level: 2, expandable: false },
    { item: "Specific", level: 2, expandable: false },
    { item: "VaR (95%, 2 weeks, Chebyshev)", level: 1, expandable: true },
    { item: "Total", level: 2, expandable: false },
    { item: "Systematic", level: 2, expandable: false },
    { item: "Specific", level: 2, expandable: false }
  ],
  expected: {
    "Risk Analysis": {
      "Volatility": ["Total", "Systematic", "Specific"],
      "TaR (68%, 1 year)": ["Total", "Systematic", "Specific"],
      "VaR (95%, 2 weeks, Chebyshev)": ["Total", "Systematic", "Specific"]
    }
  }
}, {
  data: [
    { item: "Risk Analysis", level: 0, expandable: true },
    { item: "Standard", level: 1, expandable: true },
    { item: "Active", level: 2, expandable: true },
    { item: "Volatility", level: 3, expandable: true },
    { item: "Contribution", level: 4, expandable: true },
    { item: "Total", level: 5, expandable: false },
    { item: "Systematic", level: 5, expandable: false },
    { item: "Specific", level: 5, expandable: false }
  ],
  expected: {
    "Risk Analysis": {
      "Standard": {
        "Active": {
          "Volatility": {
            "Contribution": [ "Total", "Systematic", "Specific" ]
          }
        }
      }
    }
  }
}, {
  data: [
    { item: "Risk Analysis", level: 0, expandable: true },
    { item: "Standard", level: 1, expandable: true },
    { item: "Active", level: 2, expandable: true },
    { item: "Volatility", level: 3, expandable: true },
    { item: "Contribution", level: 4, expandable: true },
    { item: "Total", level: 5, expandable: false },
    { item: "Systematic", level: 5, expandable: false },
    { item: "Specific", level: 5, expandable: false },
    { item: "VaR (95%, 2 weeks, Chebyshev)", level: 3, expandable: true },
    { item: "Contribution", level: 4, expandable: true },
    { item: "Total", level: 5, expandable: false },
    { item: "Systematic", level: 5, expandable: false },
    { item: "Specific", level: 5, expandable: false },
    { item: "Benchmark", level: 2, expandable: true },
    { item: "Volatility", level: 3, expandable: true },
    { item: "Contribution", level: 4, expandable: true },
    { item: "Total", level: 5, expandable: false },
    { item: "Systematic", level: 5, expandable: false },
    { item: "Specific", level: 5, expandable: false },
    { item: "VaR (95%, 2 weeks, Chebyshev)", level: 3, expandable: true },
    { item: "Contribution", level: 4, expandable: true },
    { item: "Total", level: 5, expandable: false },
    { item: "Systematic", level: 5, expandable: false },
    { item: "Specific", level: 5, expandable: false },
    { item: "Portfolio", level: 2, expandable: true },
    { item: "Volatility", level: 3, expandable: true },
    { item: "Contribution", level: 4, expandable: true },
    { item: "Total", level: 5, expandable: false },
    { item: "Systematic", level: 5, expandable: false },
    { item: "Specific", level: 5, expandable: false },
    { item: "VaR (95%, 2 weeks, Chebyshev)", level: 3, expandable: true },
    { item: "Contribution", level: 4, expandable: true },
    { item: "Total", level: 5, expandable: false },
    { item: "Systematic", level: 5, expandable: false },
    { item: "Specific", level: 5, expandable: false }
  ],
  expected: {
    "Risk Analysis": {
      "Standard": {
        "Active": {
          "Volatility": {
            "Contribution": ["Total", "Systematic", "Specific"]
          },
          "VaR (95%, 2 weeks, Chebyshev)": {
            "Contribution": ["Total", "Systematic", "Specific"]
          }
        },
        "Benchmark": {
          "Volatility": {
            "Contribution": ["Total", "Systematic", "Specific"]
          },
          "VaR (95%, 2 weeks, Chebyshev)": {
            "Contribution": ["Total", "Systematic", "Specific"]
          }
        },
        "Portfolio": {
          "Volatility": {
            "Contribution": ["Total", "Systematic", "Specific"]
          },
          "VaR (95%, 2 weeks, Chebyshev)": {
            "Contribution": ["Total", "Systematic", "Specific"]
          }
        },
      }
    }
  }
}];

const applyRelationships = (data) => {
  let levelStack = [], lastNode = null;
  return data.map((curr, index) => {
    const node = { ...curr, id: index + 1 };
    if (levelStack.length === 0) {
      levelStack.push({ level: node.level, parent: 0 });
    } else {
      const last = levelStack[levelStack.length - 1];
      if (node.level > last.level) {
        levelStack.push({ level: node.level, parent: lastNode.id });
      } else if (node.level < last.level) {
        const
          levelDiff = last.level - node.level - 1,
          lastIndex = levelStack.length - 1;
        levelStack.splice(lastIndex - levelDiff, lastIndex);
      }
    }
    node.parentId = levelStack[levelStack.length - 1].parent;
    lastNode = node;
    return node;
  });
};

const listToTree = (arr = []) => {
   let indexMap = new Map();
   arr.forEach((node, index) => {
      indexMap.set(node.id, index)
      node.children = [];
   });
   return arr.reduce((res, node, index, all) => {
      if (node.parentId === 0) return [...res, node];
      all[indexMap.get(node.parentId)].children.push(node);
      return res;
   }, []);
};

const treeToObject = (tree = [], result = {}) => {
  tree.forEach(child => {
    if (!child.expandable) {
      result.push(child.item);
    } else {
      const childrenAllEmpty = child.children
        .every(({ children }) => children.length === 0);
      result[child.item] = childrenAllEmpty ? [] : {};
      treeToObject(child.children, result[child.item]);
    }
  });
  return result;
};

const buildTreeObject = (arr = []) =>
  treeToObject(listToTree(applyRelationships(arr)));
  
main();
代码语言:javascript
复制
.as-console-wrapper { top: 0; max-height: 100% !important; }

原始响应

代码语言:javascript
复制
const main = () => {
  useCases.forEach(({ data, params: { maxDepth }, expected }) => {
    const actual = buildTreeObject(data, maxDepth);
    console.log(JSON.stringify(actual) === JSON.stringify(expected));
    console.log(actual);
  });
};

const useCases = [{
  data: [
    { item: "Risk Analysis", level: 0, expandable: true },
    { item: "Volatility", level: 1, expandable: true },
    { item: "Total", level: 2, expandable: false },
    { item: "Systematic", level: 2, expandable: false },
    { item: "Specific", level: 2, expandable: false },
    { item: "TaR (68%, 1 year)", level: 1, expandable: true },
    { item: "Total", level: 2, expandable: false },
    { item: "Systematic", level: 2, expandable: false },
    { item: "Specific", level: 2, expandable: false },
    { item: "VaR (95%, 2 weeks, Chebyshev)", level: 1, expandable: true },
    { item: "Total", level: 2, expandable: false },
    { item: "Systematic", level: 2, expandable: false },
    { item: "Specific", level: 2, expandable: false }
  ],
  params : { maxDepth: 1 },
  expected: {
    "Risk Analysis": {
      "Volatility": ["Total", "Systematic", "Specific"],
      "TaR (68%, 1 year)": ["Total", "Systematic", "Specific"],
      "VaR (95%, 2 weeks, Chebyshev)": ["Total", "Systematic", "Specific"]
    }
  }
}, {
  data: [
    { item: "Risk Analysis", level: 0, expandable: true },
    { item: "Standard", level: 1, expandable: true },
    { item: "Active", level: 2, expandable: true },
    { item: "Volatility", level: 3, expandable: true },
    { item: "Contribution", level: 4, expandable: true },
    { item: "Total", level: 5, expandable: false },
    { item: "Systematic", level: 5, expandable: false },
    { item: "Specific", level: 5, expandable: false }
  ],
  params: { maxDepth: 4 },
  expected: {
    "Risk Analysis": {
      "Standard": {
        "Active": {
          "Volatility": {
            "Contribution": [ "Total", "Systematic", "Specific" ]
          }
        }
      }
    }
  }
}];

const applyRelationships = (data) => {
  let levelStack = [], lastNode = null;
  return data.map((curr, index) => {
    const node = { ...curr, id: index + 1 };
    if (levelStack.length === 0) {
      levelStack.push({ level: node.level, parent: 0 });
    } else {
      const last = levelStack[levelStack.length - 1];
      if (node.level > last.level) {
        levelStack.push({ level: node.level, parent: lastNode.id });
      } else if (node.level < last.level) {
        levelStack.pop();
      }
    }
    node.parentId = levelStack[levelStack.length - 1].parent;
    lastNode = node;
    return node;
  });
};

const listToTree = (arr = []) => {
   let indexMap = new Map();
   arr.forEach((node, index) => {
      indexMap.set(node.id, index)
      node.children = [];
   });
   return arr.reduce((res, node, index, all) => {
      if (node.parentId === 0) return [...res, node];
      all[indexMap.get(node.parentId)].children.push(node);
      return res;
   }, []);
};

const treeToObject = (tree, maxDepth = 1, result = {}) => {
  tree.forEach(child => {
    result[child.item] = {};
    if (child.level >= maxDepth) {
      result[child.item] = child.children.map(({ item }) => item);
    } else {
      treeToObject(child.children, maxDepth, result[child.item]);
    }
  });
  return result;
};

const buildTreeObject = (arr = [], maxDepth = 1) =>
  treeToObject(listToTree(applyRelationships(arr)), maxDepth);
  
main();
代码语言:javascript
复制
.as-console-wrapper { top: 0; max-height: 100% !important; }

票数 1
EN

Stack Overflow用户

发布于 2022-11-15 13:41:54

角材料树到JSON对象转换器。

代码语言:javascript
复制
export class TodoItemNode {
  children: TodoItemNode[];
  item: string;
}

treeToObject(result: any, nodes: TodoItemNode[]): any {
 for (const node of nodes) {
  if (node.children && node.children.length > 0) {
    let isArray = true;
    for (const child of node.children) {
      if (child.children && child.children.length > 0) {
        isArray = false;
        break;
      }
    }
    if (isArray) {
      result[node.item] = [];
      for (const child of node.children) {
        result[node.item].push(child.item);
      }
    } else {
      result[node.item] = {};
      this.treeToObject(result[node.item], node.children);
    }
  } else {
    result[node.item] = null;
  }
 }
 return result;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67738546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档