假设您必须关注数据(已从数据库加载):
var data = [
{ _id: "MongoDB", children: [] },
{ _id: "Postgres", children: [] },
{ _id: "Databases", children: [ "MongoDB", "Postgres" ] },
{ _id: "Languages", children: [] },
{ _id: "Programming", children: [ "Databases", "Languages" ] },
{ _id: "Books", children: [ "Programming" ] }
];
由于_id
是唯一的,因此在第一步中将其转换为字典,其中键是 id:
var dct = {};
for (var i = 0; i < data.length; i++) {
var doc = data[i];
dct[doc._id] = doc;
}
现在您再循环data
一次数组并设置子项:
for (var i = 0; i < data.length; i++) {
var doc = data[i];
var children = doc.children;
var ref_children = [];
for (var j = 0; j < children.length; j++) {
var child = dct[children[j]]; // <-- here's where you need the dictionary
ref_children.push(child);
}
doc.children = ref_children;
}
瞧,你完成了:
JSON.stringify(data);
编辑
如果您只想要根(不是任何其他节点的子节点的节点),那么首先您必须找到它们:
var get_parent = function(node, docs) {
for (var i = 0; i < docs.length; i++) {
var doc = docs[i];
if (doc.children.indexOf(node) != -1) {
return doc;
}
}
return null;
};
var roots = [];
for (var i = 0; i < docs.length; i++) {
var doc = data[i];
if (get_parent(doc, docs) === null) {
roots.push(doc);
}
}
JSON.stringify(roots);
更有效的方法是在取消引用孩子时存储父母(与编辑上面的代码比较):
for (var i = 0; i < data.length; i++) {
var doc = data[i];
var children = doc.children;
var ref_children = [];
for (var j = 0; j < children.length; j++) {
var child = dct[children[j]]; // <-- here's where you need the dictionary
child.has_parent = true; // <-- has a parent
ref_children.push(child);
}
doc.children = ref_children;
}
var roots = [];
for (var i = 0; i < data.length; i++) {
var doc = data[i];
if (!doc.has_parent) {
roots.push(doc);
}
}
JSON.stringify(roots);