js 多子树节点值修改
自定义一个tree数组
bash
// tree data
tree = [{
id: 'D1',
label: '设备 1',
alarmColor: '#ff0000',
disabled: false,
children: [{
id: 'B1',
label: '板卡 1-1',
alarmColor: '#ffff00',
disabled: false,
children: [{
id: 'k1',
label: '端口 1-1-1',
alarmColor: '#ffff00',
disabled: false
}, {
id: 'k1-2',
label: '端口 1-1-2',
alarmColor: '#ffff00',
disabled: false
}]
}, {
id: 'B2',
label: '板卡 1-2',
alarmColor: '#ff0000',
disabled: false,
children: [{
id: 'K2',
label: '端口 1-2-1',
alarmColor: '#ff0000',
disabled: false
}]
}]
}, {
id: 'D2',
label: '设备 2',
alarmColor: '#ff0000',
disabled: false,
children: [{
id: 'B3',
label: '板卡 2-1',
alarmColor: '#ff0000',
disabled: false,
children: [{
id: 'K3',
label: '端口 2-1-1',
alarmColor: '#ff0000',
disabled: false
}]
}, {
id: 'B4',
label: '板卡 2-2',
alarmColor: '#ff0000',
disabled: true,
children: [{
id: 'K4',
label: '端口 2-2-1',
alarmColor: '#ff0000',
disabled: true
}]
}]
}, {
id: 'D3',
label: '设备 3',
alarmColor: '#ff0000',
disabled: true,
children: [{
id: 'B5',
label: '板卡 3-1',
alarmColor: '#ff0000',
disabled: true,
children: [{
id: 'K5',
label: '端口 3-1-1',
alarmColor: '#ff0000',
disabled: true
}]
}, {
id: 'B6',
label: '板卡 3-2',
alarmColor: '#ff0000',
disabled: true,
children: [{
id: 'K6',
label: '端口 3-2-1',
alarmColor: '#ff0000',
disabled: true
}]
}]
}];
需求
当子节点disable的时候,父节点也需要disable。
实现
const newArr = tree.map(item => treeMap(item))
function treeMap(data){
const hasChild = data.children && data.children.length > 0;
if( hasChild ){
var bDisabled = false;
data.children.map( i => treeMap(i)).forEach(function (item) {
if(item.disabled) {
bDisabled = true;
return;
}
});
if( bDisabled )
data.disabled = bDisabled
}
// 可以根据实际开发需要返回自己想要的key值
var jsonRet = {
id:data.id,
disabled:data.disabled,
}
return jsonRet;
}