以下递归解决方案将向您显示遇到的第一个丢失连接关系的错误。我添加了评论,以便您可以跟踪发生的情况。
它不会检查所有连接:当它找到子节点和父节点之间正确建立的连接时,它会快速移动到下一个节点。
基本上,它包括搜索每个子节点是否正确记录了当前父/子关系的连接。它应该适用于任意数量的子节点/嵌套级别。
var records = [{"name":"Node-1","nodes":[{"name":"Node-1-1","isParent":false,"nodes":[{"name":"Node-1-1-1","isParent":false,"nodes":[],"connections":{"joins":[]}}], "connections":{"joins":[{"parent":"Node-1","child":"Node-1-1"}]}}],"isParent":true}];
function connections_control(records, parent = undefined) {
// Browse the nodes list
for (var node of records) {
// Control if the keys we need do exist
if (parent && node.connections && node.connections.joins) {
var found = false;
// Search in connections the current relation parent/child
for (var connection of node.connections.joins) {
if (connection.parent == parent && connection.child == node.name) {
found = true;
break;
}
}
if (!found) {
// We checked all connections, but we did not find our current relation!
console.log('Warning: Broken connection between parent node '+parent+' and child node '+node.name);
break;
}
}
if (node.nodes) {
// The current node becomes parent, start again with the inner nodes list
connections_control(node.nodes, node.name);
}
}
}
connections_control(records);
请注意,在第一个循环中,它从根部获取文档,没有父级,因此不会搜索连接。
执行:
nodejs childs.js
Warning: Broken connection between parent node Node-1-1 and child node Node-1-1-1