我在这样存储的对象数组中有结构数据库:
arry = [{"name": "a", "id": "2", "data":"foo", "parent": "1"},
{"name": "b", "id": "3", "data":"foo", "parent": "2"},
{"name": "c", "id": "4", "data":"foo", "parent": "3"},
{"name": "d", "id": "5", "data":"foo", "parent": "3"},
{"name": "e", "id": "6", "data":"foo", "parent": "4"},
{"name": "f", "id": "7", "data":"foo", "parent": "5"}]
我想要这样的嵌套结构
{
"2":{
"name": "a",
"data": "foo",
"3":{
"name": "b",
"data":"foo",
"4":{
"name": "c",
"data":"foo",
"6":{
"name": "e",
"data": "foo",
};
},
"5":{
"name": "d",
"data": "foo",
"7":{
"name": "f",
"data": "foo"
}
}
}
}
};
所以我可以使用 Angular Material 树。
最佳答案
为此,您可以将节点数组缩减为字典,使用每个节点的 id
作为索引。
这样,您就可以通过字典中的 id 直接访问所有节点。因此,您将能够轻松地将每个节点存储在其父节点中。
一旦所有节点都存储在它们各自的父节点中,您只需从字典中获取根节点,它将包含您的所有树。
当您解析子节点时,父节点可能还不在字典中,在这种情况下,您可以使用一个虚拟对象,它会在我们解析实际父节点时充当占位符。
var arry = [
{"name": "a", "id": "2", "data":"foo", "parent": "1"},
{"name": "b", "id": "3", "data":"foo", "parent": "2"},
{"name": "c", "id": "4", "data":"foo", "parent": "3"},
{"name": "d", "id": "5", "data":"foo", "parent": "3"},
{"name": "e", "id": "6", "data":"foo", "parent": "4"},
{"name": "f", "id": "7", "data":"foo", "parent": "5"}
];
function totree(branches, node) {
// if we don't have the parent yet
if (!branches[node.parent]) {
// create a dummy placeholder for now
branches[node.parent] = {};
}
// store our node in its parent
branches[node.parent][node.id] = node;
// store our node in the full list
// copy all added branches on possible placeholder
branches[node.id] = Object.assign(node, branches[node.id]);
return branches;
}
var tree = arry.reduce(totree, {})['1']; // get only the root node ('1')
console.log(tree);
关于javascript - 在 Typescript 中将数组转换为树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52847368/