我有一个节点系统,它存储一堆连接到其他节点的节点。数据的结构如下:
[
{"id":0,"x":1,"y":2, "linksTo":[1]},
{"id":1,"x":3,"y":4, "linksTo":[0,2,3]},
{"id":2,"x":5,"y":6, "linksTo":[1,4]},
{"id":3,"x":3,"y":10,"linksTo":[1,4]},
{"id":4,"x":5,"y":12,"linksTo":[2,3]}
]
我要做的是删除某个节点,以及其他节点中对该节点的所有引用,这些节点可能会根据其ID与其“链接”。
我已经到了可以使用此功能获取所需节点的地步:
function getNode(id, y){
var x;
if(y){ x = id; }
if(x && y){
var nodeAtPos = false;
Object.keys(paths.list).forEach(function(i){
if(paths.list[i].x == x && paths.list[i].y == y){
nodeAtPos = paths.list[i];
return false;
}
return true;
});
return nodeAtPos;
}
return paths.list[id];
}
function deleteNode(x,y){
var obj = getNode(x,y);
//need to delete obejct and delete key references in other objects that were connected to it
}
deleteNode(5,12);
最终结果在我的数据结构中看起来像这样:
[
{"id":0,"x":1,"y":2, "linksTo":[1]},
{"id":1,"x":3,"y":4, "linksTo":[0,2,3]},
{"id":2,"x":5,"y":6, "linksTo":[1]}, //changed
{"id":3,"x":3,"y":10,"linksTo":[1]}, //changed
]
但正如你在我的数据结构中看到的那样,如果我只是删除它,我仍然有一些linksTo
的节点,我需要清理它。否则,它们将链接到不存在的节点。
最简单的方法是什么?
答案 0 :(得分:2)
您可以iterate
每个对象并执行以下操作:
node
是否有链接。如果是这样,将其从中删除
linkTo
。index
其id
作为要删除的节点。remove
数组中的节点。代码:
var x = [
{"id":0,"x":1,"y":2, "linksTo":[1]},
{"id":1,"x":3,"y":4, "linksTo":[0,2,3]},
{"id":2,"x":5,"y":6, "linksTo":[1,4]},
{"id":3,"x":3,"y":10,"linksTo":[1,4]},
{"id":4,"x":5,"y":12,"linksTo":[2,3]}
];
var index = -1;
var toDel = 2;
for(var i=0;i<x.length;i++){
if(x[i]["linksTo"].indexOf(toDel) != -1){
x[i]["linksTo"].splice(x[i]["linksTo"].indexOf(toDel),1);
}
if(x[i]["id"] == toDel){index = i;}
}
if(index != -1){
x.splice(index, 1);
}
console.log(x);
答案 1 :(得分:0)
没有其他方法,但更新其余元素的linksTo值
var deletedId = 4;
var arr = [
{"id":0,"x":1,"y":2, "linksTo":[1]},
{"id":1,"x":3,"y":4, "linksTo":[0,2,3]},
{"id":2,"x":5,"y":6, "linksTo":[1,4]},
{"id":3,"x":3,"y":10,"linksTo":[1,4]},
];
for (var i=0 ; i < arr.length ; i++ ) {
var node = arr[i];
var newRef = [];
for (var l=0 ; l < node.linksTo.length; l++) { // l is an index for links
if (node.linksTo[l] != deletedId)
newRef.push(node.linksTo[l])
}
node.linksTo = newRef; // assign new array
}