javascript - 如何获取树的每个节点的父母和所有孩子的数组?
问题描述
我有一种数据,图中就是它的一个例子
[
{
id: "1",
parentId: "0"
},
{
id: "2",
parentId: "0",
},
{
id: "3",
parentId: "1"
},
{
id: "4",
parentId: "2"
}
]
如何获取每个节点的父节点和所有子节点的数组。
例如:
Input: 1
Output: [0,1,3]
Input: 3
Output: [0,1,3]
Input: 0
Output: [0,1,3],[0,2,4]
解决方案
所以这里有一个非常粗略的代码来实现你想要实现的。当然可以改进,但我认为在功能上这应该可以工作->
start: function() {
var arr = [
{
id: "1",
parentId: "0",
},
{
id: "2",
parentId: "0",
},
{
id: "3",
parentId: "1",
},
{
id: "4",
parentId: "2",
},
];
var out = [];
var input = "2";
var finalOut = [];
this.getParentArray(arr, input, out);
console.log("out", out);
this.getChildArray(arr, input, out, finalOut);
console.log("finalOut", finalOut);
}
/**
* Get parents of the input
*/
getParentArray: function(flatArray = [], input, output = []) {
// Find the node
let node = flatArray.find((f) => f.id == input);
if (node) {
output.unshift(node.id);
// Find parent of the node
let parentNode = flatArray.find((f) => f.id == node.parentId);
if (parentNode) {
// If parent node has further parents, do recursion to get all parents
if (flatArray.findIndex((f) => f.id == parentNode.parentId) != -1) {
this.getParentArray(flatArray, parentNode.id, output);
} else {
// Add parent and it's parent id to the output
output.unshift(parentNode.id);
output.unshift(parentNode.parentId);
}
} else {
// If no parent, add the node parent id on top
output.unshift(node.parentId);
}
} else if (flatArray.findIndex((f) => f.parentId == input) != -1) {
// If no node found and the input exists as parent id to some element, then add this input in the last
output.push(input);
}
}
/**
* Get children of the array
*/
getChildArray: function(flatArray = [], input, output = [], finalOutput = []) {
// Get all children of the input
let children = flatArray.filter((f) => f.parentId == input);
// Create a middle point to hold the data
let midOutput = JSON.parse(JSON.stringify(output));
if (!children || children.length == 0) {
// If no children, just push the output to final output
finalOutput.push(output);
return;
}
children.forEach((child, index) => {
midOutput = JSON.parse(JSON.stringify(output));
if (child) {
midOutput.push(child.id);
// Recursion if child has more children
if (flatArray.findIndex((f) => f.parentId == child.id) != -1) {
this.getChildArray(flatArray, child.id, midOutput, finalOutput);
} else {
finalOutput.push(JSON.parse(JSON.stringify(midOutput)));
}
}
});
}
推荐阅读
- python - python自动统计线性回归
- c# - 为什么 Grid CurrentRow.index 不包含网格线选择?
- amazon-cloudformation - 将 CommaDelimitedList of Roles 转换为 Cloudformation 中的 Arns 列表
- boost - 在 appveyor 中使用 boost 库
- javascript - Node-Red 多个输出到 CSV
- python - 了解 Seaborn 中的箱线图
- javascript - 将 createObjectURL 的结果分配给图像无法在移动 Safari 上加载资源
- laravel - 如何使用 javascript 加载私有 Amazon S3 文件?
- javascript - 从剑道编辑器获取没有标记的文本
- c# - 如何将字符串资源文件导入表单的资源文件?