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

如何在Angular中将JSON数组转换为基于label属性的对象树

JSON数组转Label键嵌套对象树实现方案

你给出的示例输出中Phones节点下的Sbardilate、Balons未包含在输入数组中,实际运行时会根据你传入的数组内容自动生成对应结构。

转换函数(兼容Angular TypeScript环境)

interface TreeNode {
  id: number;
  label: string;
  parent_id: number;
  [key: string]: any;
}

function buildLabelTree(arr: TreeNode[]): Record<string, any> {
  // 构建id到节点的映射表,减少重复遍历开销
  const idNodeMap = new Map<number, TreeNode>();
  arr.forEach(item => idNodeMap.set(item.id, {...item}));

  // 递归生成嵌套结构
  const getChildTree = (parentId: number): Record<string, any> | null => {
    const childNodes = arr.filter(item => item.parent_id === parentId);
    if (childNodes.length === 0) return null;

    const tree: Record<string, any> = {};
    childNodes.forEach(node => {
      tree[node.label] = getChildTree(node.id);
    });
    return tree;
  };

  // 根节点默认parent_id为0
  return getChildTree(0);
}

调用示例

// 你的输入JSON数组
const inputArray = [
  {
    "id": 2,
    "label": "BEAUTY",
    "description": "",
    "parent_id": 0,
  },
  {
    "id": 5,
    "label": "SunGlass",
    "description": "",
    "parent_id": 2,
  },
  {
    "id": 6,
    "label": "Shirts",
    "description": "",
    "parent_id": 2,
  },
  {
    "id": 41,
    "label": "black Glasses",
    "description": "electronique",
    "parent_id": 5,
  },
  {
    "id": 34,
    "label": "T-shirts",
    "description": "electronique",
    "parent_id": 6,
  },
  {
    "id": 3,
    "label": "Phones",
    "description": "",
    "parent_id": 0,
    "embedded_parent": null,
  }
];

// 转换结果直接赋值给TREE_DATA即可传入组件使用
const TREE_DATA = buildLabelTree(inputArray);

输出结果

{
  BEAUTY: {
    'SunGlass': { 'black Glasses': null },
    'Shirts': { 'T-shirts': null }
  },
  Phones: null
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 19:21:02