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

如何在多维JSON结构中添加或更新节点?

房屋层级结构的节点维护方案(JavaScript实现)

示例初始数据

先定义一个符合结构的房屋JSON数组,用于后续操作演示:

const houseStructure = [
  {
    id: '1',
    code: '1',
    name: 'Smith家',
    children: [
      {
        id: '1-1',
        code: '1-1',
        name: '客厅',
        children: []
      },
      {
        id: '1-2',
        code: '1-2',
        name: '厨房',
        children: []
      }
    ]
  }
];

核心:递归查找目标节点

实现通用递归函数,通过code匹配定位目标节点,这是添加、更新操作的基础:

function findNodeByCode(nodes, targetCode) {
  for (const node of nodes) {
    if (node.code === targetCode) {
      return node;
    }
    // 递归遍历子节点
    if (node.children && node.children.length > 0) {
      const found = findNodeByCode(node.children, targetCode);
      if (found) return found;
    }
  }
  return null; // 未找到节点返回null
}

1. 节点添加操作

通过父节点code定位目标位置,支持添加带嵌套子节点的新节点:

function addNode(nodes, parentCode, newNode) {
  const parentNode = findNodeByCode(nodes, parentCode);
  if (!parentNode) {
    console.error(`未找到code为${parentCode}的父节点`);
    return false;
  }
  // 确保父节点存在children数组
  if (!parentNode.children) {
    parentNode.children = [];
  }
  parentNode.children.push(newNode);
  return true;
}

添加示例

  • 给Smith家的客厅(code: 1-1)添加地毯
  • 给厨房(code: 1-2)添加带子节点的微波炉
// 给客厅添加地毯
addNode(houseStructure, '1-1', {
  id: '1-1-1',
  code: '1-1-1',
  name: '地毯',
  children: []
});

// 给厨房添加微波炉及其子节点
addNode(houseStructure, '1-2', {
  id: '1-2-1',
  code: '1-2-1',
  name: '微波炉',
  children: [
    {
      id: '1-2-1-1',
      code: '1-2-1-1',
      name: '加热盘',
      children: []
    },
    {
      id: '1-2-1-2',
      code: '1-2-1-2',
      name: '控制面板',
      children: []
    }
  ]
});

2. 节点更新操作

通过目标节点code定位后,批量更新节点属性(不覆盖未指定的原有属性):

function updateNode(nodes, targetCode, updates) {
  const targetNode = findNodeByCode(nodes, targetCode);
  if (!targetNode) {
    console.error(`未找到code为${targetCode}的节点`);
    return false;
  }
  // 合并更新属性
  Object.assign(targetNode, updates);
  return true;
}

更新示例

将Smith家的客厅名称改为“大客厅”:

updateNode(houseStructure, '1-1', { name: '大客厅' });

扩展说明

  • 若需支持删除节点,可基于findNodeByCode扩展逻辑,记录目标节点的父节点后,从父节点的children数组中移除目标节点
  • 可封装自动生成code和id的逻辑(比如基于父节点code拼接序号),避免手动输入出错
  • 如需避免修改原始数据,可先对结构进行深拷贝(例如JSON.parse(JSON.stringify(nodes)))再执行操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:06:25