vue页面左右两侧有两棵树,树上有目录和镜头,将左侧树上与右侧树上重复的目录和镜头删去,如果左侧目录下存在右侧树上没有的镜头则保留目录,左侧树数组为 aaa=[ { name:1111, guid:'1111', children:[ { name:2222, guid:'2222', children:[ { name:2222, guid:'2222', children:[] }, { name:3333, guid:'3333', children:[] }, { name:4444, guid:'4444', children:[] } ] }, { name:5555, guid:'5555', children:[ { name:6666, guid:'6666', children:[] }, { name:7777, guid:'7777', children:[] } ] } ] } ] 右侧树数组为: bbb=[ { name:2222, guid:'2222', children:[ { name:2222, guid:'2222', children:[] }, { name:4444, guid:'4444', children:[] } ] }, { name:5555, guid:'5555', children:[ { name:6666, guid:'6666', children:[] }, { name:7777, guid:'7777', children:[] } ] } ]
时间: 2024-04-15 11:29:23 浏览: 54
vue实现树形结构样式和功能的实例代码
根据您提供的左侧树和右侧树的数组,可以使用以下代码实现删除左侧树上与右侧树上重复的目录和镜头,同时保留左侧目录下存在右侧树上没有的镜头:
```javascript
function removeDuplicates(leftTree, rightTree) {
for (let i = leftTree.length - 1; i >= 0; i--) {
const leftNode = leftTree[i];
const rightNode = findNode(rightTree, leftNode.guid);
if (rightNode) {
// 左侧树节点存在于右侧树中,继续递归检查子节点
removeDuplicates(leftNode.children, rightNode.children);
if (leftNode.children.length === 0) {
// 如果左侧节点的子节点全部被删除,则删除当前节点
leftTree.splice(i, 1);
}
} else {
// 左侧树节点不存在于右侧树中,保留该节点
removeDuplicates(leftNode.children, []);
}
}
}
function findNode(tree, guid) {
for (const node of tree) {
if (node.guid === guid) {
return node;
}
const foundNode = findNode(node.children, guid);
if (foundNode) {
return foundNode;
}
}
return null;
}
// 使用示例
const aaa = [
{
name: '1111',
guid: '1111',
children: [
{
name: '2222',
guid: '2222',
children: [
{
name: '2222',
guid: '2222',
children: []
},
{
name: '3333',
guid: '3333',
children: []
},
{
name: '4444',
guid: '4444',
children: []
}
]
},
{
name: '5555',
guid: '5555',
children: [
{
name: '6666',
guid: '6666',
children: []
},
{
name: '7777',
guid: '7777',
children: []
}
]
}
]
}
];
const bbb = [
{
name: '2222',
guid: '2222',
children: [
{
name: '2222',
guid: '2222',
children: []
},
{
name: '4444',
guid: '4444',
children: []
}
]
},
{
name: '5555',
guid: '5555',
children: [
{
name: '6666',
guid: '6666',
children: []
},
{
name: '7777',
guid: '7777',
children: []
}
]
}
];
removeDuplicates(aaa, bbb);
console.log(aaa);
```
运行上述代码后,`aaa` 数组中将只保留左侧树上与右侧树上重复的目录和镜头被删除,同时保留左侧目录下存在右侧树上没有的镜头。可以在浏览器的开发者工具中查看输出结果。
阅读全文