[英]Getting all the children of a tree javascript object as a flat array
I have a tree-based javascript object.我有一个基于树的 javascript object。
let tree = {
id: 1, children: [
{id: 2},
{id: 3},
{
id: 4, children: [
{id: 5},
{id: 6},
{
id: 7, children: [
{id: 8},
{id: 9},
{id: 10,}
]
}
]
}
]
}
So, im trying to get all of them as a flat array, like this:所以,我试图将它们全部作为一个平面数组,如下所示:
let flattenedTree = [
{ id: 1, children: [ /*All of it children...*/ ] },
{ id: 2 },
{ id: 3 },
{ id: 4, children: [ /*All of it children...*/ ] },
{ id: 5 },
{ id: 6 },
{ id: 7, children: [ /*All of it children...*/ ] },
{ id: 8 },
{ id: 9 },
{ id: 10 }
]
What options do i have to get them all without doing some dirty spaguetti code?在不做一些肮脏的意大利面条代码的情况下,我有什么选择? I tried using array.forEach()
but it naturally requires doing another iteration inside it, and surely will require it again while doing in this way, Thanks for the help =)我尝试使用array.forEach()
但它自然需要在其中进行另一次迭代,并且在这样做时肯定会再次需要它,感谢您的帮助 =)
Recursion is the best choice to work with trees.递归是处理树的最佳选择。 It allows you to do this without spaghetti code:它允许您在没有意大利面条代码的情况下执行此操作:
function treeToList(tree) {
const result = [];
result.push(tree);
const children = tree.children || [];
children.forEach(child => {
const childResult = treeToList(child);
result.push(...childResult)
})
return result;
}
treeToList(tree)
Recursion should be used when such object.此类 object 时应使用递归。 Writing every loop function will be a boring and time wasting option.编写每个循环 function 将是一个无聊且浪费时间的选择。 Recursion will function itself to the end branch of the object.将 function 自身递归到 object 的末端分支。
// changed tree variable from object to array
// because object or array with recursion has same data type
let tree = [
id: 1, children: [
{id: 2},
{id: 3},
{
id: 4, children: [
{id: 5},
{id: 6},
{
id: 7, children: [
{id: 8},
{id: 9},
{id: 10,}
]
}
]
}
]
]
function recursion(obj) {
obj.forEach((value, idx) => {
// this condition will check if the value is array to do recursion
if (typeof subObj === 'array') {
return recursion(value)
} else {
// if the value is not an array to do recursion,
// it will do what you want to do with this function
//and then will be finished.
// do what date would be handled by recursion
// ex) value = 'new value'
return
}
})
return
}
recursion(tree)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.