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

如何将给定JSON对象转换为Angular Material树形结构所需格式?

将原始JSON转换为Angular Material树形结构的方法

针对你提供的JSON结构,下面两种方法可以将其转换为Angular Material树形组件所需的{name: string, children?: TreeNode[]}格式。

一、手动转换(适合固定结构场景)

因为你的原始JSON层级和节点数量固定,直接提取对应字段即可完成转换,逻辑简单直观:

function convertToTreeStructure(rawData) {
  // 构建根节点
  const root = {
    name: rawData.Parent,
    children: []
  };

  // 构建fruit子节点
  const fruitNode = {
    name: 'fruit',
    children: []
  };
  root.children.push(fruitNode);

  // 构建Apple子节点
  const appleNode = {
    name: 'Apple',
    children: []
  };
  fruitNode.children.push(appleNode);

  // 提取颜色节点:遍历appleColours数组,取每个对象的键作为name
  const colourNodes = rawData.fruit[0].Apple[0].Child3[0].appleColours.map(colourObj => {
    return { name: Object.keys(colourObj)[0] };
  });
  appleNode.children.push(...colourNodes);

  return root;
}

// 你的原始JSON数据
const rawJson = {
  "Parent": "Tree",
  "fruit": [
    {
      "fruitNumber": 1,
      "Apple": [
        {
          "appleNumber": 1,
          "Child3": [
            {
              "child3Number": 1,
              "colours": 3,
              "appleColours": [
                { "greenApple": 1 },
                { "redApple": 2 },
                { "yelloApple": 3 }
              ]
            }
          ]
        }
      ]
    }
  ]
};

// 执行转换
const treeData = convertToTreeStructure(rawJson);
console.log(JSON.stringify(treeData, null, 2));

执行后会输出目标结构:

{
  "name": "Tree",
  "children": [
    {
      "name": "fruit",
      "children": [
        {
          "name": "Apple",
          "children": [
            { "name": "greenApple" },
            { "name": "redApple" },
            { "name": "yelloApple" }
          ]
        }
      ]
    }
  ]
}

代码说明

  • 按层级提取原始JSON中的字段,比如从rawData.fruit[0]取第一个fruit元素(你的数组仅包含一个元素)
  • 用map遍历appleColours数组,通过Object.keys(colourObj)[0]提取每个颜色对象的键作为节点名称
  • 跳过fruitNumber、appleNumber这类数值型属性,因为目标结构不需要这些数据

二、递归转换(适合动态/可变结构)

如果你的JSON结构可能变化(比如新增多个fruit、Apple节点),可以用递归方法自动遍历所有层级,生成树形结构:

function buildTreeNode(data, nodeName) {
  const treeNode = { name: nodeName };
  const children = [];

  for (const key in data) {
    if (Array.isArray(data[key])) {
      // 处理数组类型的属性
      for (const item of data[key]) {
        if (typeof item === 'object' && item !== null) {
          const keys = Object.keys(item);
          // 判断是否是颜色节点(仅含一个键值对的对象)
          if (keys.length === 1 && typeof item[keys[0]] === 'number') {
            children.push({ name: keys[0] });
          } else {
            // 递归构建子节点
            children.push(buildTreeNode(item, key));
          }
        }
      }
    } else if (typeof data[key] === 'object' && data[key] !== null) {
      // 处理对象类型的属性
      children.push(buildTreeNode(data[key], key));
    }
    // 跳过数值、字符串类型的冗余属性
  }

  if (children.length > 0) {
    treeNode.children = children;
  }

  return treeNode;
}

// 构建根节点并处理其他属性
const rootNode = {
  name: rawJson.Parent,
  children: []
};

for (const key in rawJson) {
  if (key !== 'Parent') {
    rootNode.children.push(buildTreeNode(rawJson[key], key));
  }
}

console.log(JSON.stringify(rootNode, null, 2));

代码说明

  • 递归遍历JSON的每个层级,自动识别数组、对象类型的属性
  • 自动过滤数值型的冗余属性(比如fruitNumber)
  • 针对appleColours这类单一键值对的对象,直接提取键作为节点名称
  • 即使后续JSON结构扩展(比如新增多个fruit或Apple节点),代码也能自动适配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:43:12