我将以我想要做的事开始我的问题。我有一个数组(名称列表),在我的数组中我持有对象。这些对象由人的姓名(杰克,简,詹姆斯,丹尼尔等)以及这些人相关的数组组成(杰克与丹尼尔等有关)。当然,一个人可以与多于一个人有关,但两个孩子不能关联。我想把它们留在一棵树中,我希望这棵树能够根据关系。我想从与关系最密切的人开始(例如:丹尼尔与7人有关)。我知道可能有超过1人的关系最密切。但为了简单的问题,我问,让我们只是说我知道它是谁,我会通过它作为mostRelated。使用数组创建树
This is just an example of what I want to do
这是我有这么far.But我不知道如何进一步它。
//my array of names is nameList
//to check who they are related to nameList.relatedTo
function Node(names) {
this.data = names;
this.parent = null;
this.children = [];
}
function CreateTree(nameList, mostRelated)
{
this._root=mostLinked;
for(var i=0; i < nameList[i].length;i++)
{
node= new Node(nameList[i]);
if(nameList[i].isChecked!)//if already add to the tree
{
if(nameList[i].isRelated)//to check if they have any relation
{
for(var j=0; i < nameList[i].relatedTo[j].length;j++)
{
if(nameList[i].relatedTo.isChecked!)
{
nameList[i]=Node.parent;
Node.children.push(nameList[i].relatedTo[j]);
nameList[i].isChecked=true;
}
}
}
}
}
}
名称列表看起来像这样
nameList
this.name;
this.relatedTo=[];
this.related=false;
this.checked=false;
为此使用树不是正确的数据结构 - 如果两个孩子也有关系?您需要使用图表/地图 – ControlAltDel
您的设置已遍布全球。你不是已经确定谁是谁的父母/孩子吗?为了在已经提供信息的地方绘制数据图,您已经制作了一张图。举一个'nameList'的一个元素的例子。我可能会误解你的目标。 – Andrew
@ControlAltDel,感谢您的建议。但我可以让2个孩子不相关。我改变了这个问题。 – JJD