需求说明:当一个节点值为特定值的时候,改变该节点下另外一个值。
实现思路如下:
代码如下实现:
//报文结构
var arr = [{
id: 1,
pid: 0,
name: "大良造菜单",
open: true,
nocheck: false,
children: [{
id: 11,
pid: 1,
name: "当前项目"
},
{
id: 12,
pid: 1,
name: "工程管理",
open: true,
children: [{
id: 121,
pid: 12,
name: "我的工程"
},
{
id: 122,
pid: 12,
name: "施工调度"
},
{
id: 1211,
pid: 12,
name: "材料竞价"
}
]
},
{
id: 13,
pid: 1,
name: "录入管理",
open: true,
children: [{
id: 131,
pid: 12,
name: "用工录入",
children: [],
isParent: false
},
{
id: 132,
pid: 12,
name: "商家录入"
},
{
id: 1314,
pid: 12,
name: "机构列表"
}
]
},
{
id: 14,
pid: 1,
name: "审核管理",
open: true,
children: [{
id: 141,
pid: 14,
name: "用工审核"
},
{
id: 142,
pid: 14,
name: "商家审核"
},
{
id: 145,
pid: 14,
name: "机构审核"
}
]
},
{
id: 15,
pid: 1,
name: "公司管理",
open: false,
children: [{
id: 1517,
pid: 15,
name: "我的工程案例"
},
{
id: 1518,
pid: 15,
name: "联系人设置"
},
{
id: 1519,
pid: 15,
name: "广告设置"
}
]
},
{
id: 16,
pid: 1,
name: "业务管理",
open: true,
children: [{
id: 164,
pid: 16,
name: "合同范本"
},
{
id: 165,
pid: 16,
name: "合同列表"
},
{
id: 166,
pid: 16,
name: "需求调度"
}
]
},
{
id: 17,
pid: "x",
name: "订单管理",
open: true,
children: [{
id: 171,
pid: 17,
name: "商品订单"
},
{
id: 172,
pid: 17,
name: "用工订单"
},
{
id: 175,
pid: 17,
name: "供应菜单"
}
]
}
]
}];
function treeForeach(tree, func) {
tree.map(data => {
func(data)
data.children && treeForeach(data.children, func) // 遍历子树
})
}
treeForeach(arr, node => {
if (node.pid == 'x'){
node.name = "666";
}
console.log(arr);
// console.log(arr);
})
整体代码偏简练,不断的调用子树,知道最深层结构为止。