【发布时间】:2026-02-14 12:10:02
【问题描述】:
我有一个如下所示的数据结构
ds: [
{ id: "0a12", pos: 0, name: "PH1" },
{
id: "8f83",
name: "PH2",
pos: 1,
children: [
{ id: "ll54", pos: 0, name: "L1" },
{
id: "97cs",
name: "L2",
pos: 1,
children: [
{ id: "80s3", pos: 0, name: "LL1" },
{ id: "2dh3", pos: 1, name: "LL2" },
],
},
],
},
{ id: "75fd", pos: 2, name: "PH3" },
{ id: "34jg", pos: 3, name: "PH4" },
],
我正在创建一个组织结构图,其中我可以选择在左侧或右侧添加一个节点。 单击节点时,如果单击“LL1”,我可以获得节点 obj 作为参数(即),我可以获得该对象,以及称为类型的第二个参数,它将包含“左”或“右”。
所以现在 type == 'left' 那么我的结果数据结构应该是这样的
ds: [
{ id: "0a12", pos: 0, name: "PH1" },
{
id: "8f83",
name: "PH2",
pos: 1,
children: [
{ id: "4", pos: 0, name: "L1" },
{
id: "5",
name: "L2",
pos: 1,
children: [
{ id: "36fd", pos: 0, name: "" }, // new node for type === 'left'
{ id: "80s3", pos: 1, name: "LL1" },
{ id: "2dh3", pos: 2, name: "LL2" },
],
},
],
},
{ id: "75fd", pos: 2, name: "PH3" },
{ id: "34jg", pos: 3, name: "PH4" },
],
如果类型 === 'right'
ds: [
{ id: "0a12", pos: 0, name: "PH1" },
{
id: "8f83",
name: "PH2",
pos: 1,
children: [
{ id: "4", pos: 0, name: "L1" },
{
id: "5",
name: "L2",
pos: 1,
children: [
{ id: "80s3", pos: 0, name: "LL1" },
{ id: "36fd", pos: 1, name: "" }, // new node for type === 'right'
{ id: "2dh3", pos: 2, name: "LL2" },
],
},
],
},
{ id: "75fd", pos: 2, name: "PH3" },
{ id: "34jg", pos: 3, name: "PH4" },
],
注意:对于那些没有子节点的节点,我们不应该将空数组初始化为 children 属性
【问题讨论】:
标签: javascript arrays vue.js vuejs2 nested