检索属性“x”属性“y”内的所有对象的带有递归
考虑以下示例:
<script>
var McDuffFamily = {
name: "Jack McDuff I",
children: [
{
name:"Jack McDuff II",
children: [
{
name:"Jack McDuff III",
children: [
{
name:"Jack McDuff IV"
},
{
name:"Jonh McDuff I",
children: [
{
name:"Jonh McDuff I",
children: []
}
]
}
]
},
{
name:"Shena McDuff"
}
]
},
{
name:"Poor bastard",
children: [
{
name:"Citzen I",
children: [
{
name:"Darth Vader"
}
]
},
{
name:"Citzen II",
children: []
}
]
}
]
};
</script>
是否有任何轻松的方法来检索所有“Jack McDuff I”后代的姓名?
Consider the following example:
<script>
var McDuffFamily = {
name: "Jack McDuff I",
children: [
{
name:"Jack McDuff II",
children: [
{
name:"Jack McDuff III",
children: [
{
name:"Jack McDuff IV"
},
{
name:"Jonh McDuff I",
children: [
{
name:"Jonh McDuff I",
children: []
}
]
}
]
},
{
name:"Shena McDuff"
}
]
},
{
name:"Poor bastard",
children: [
{
name:"Citzen I",
children: [
{
name:"Darth Vader"
}
]
},
{
name:"Citzen II",
children: []
}
]
}
]
};
</script>
Is there any painless way to retrieve the names of all "Jack McDuff I" descendents?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不使用递归:
奇怪部分的分解:
tree[i] &&
与 短路评估 确保我调用时tree[i]
不为空tree[i].children
tree.push.apply(tree, tree[i].childrens);
使用apply 允许我调用函数,在本例中 Array.push,它在树上接受任意数量的参数
。所以该行基本上变成了tree.push(child0, child1, ... childn);。所以现在
tree.length
已经增加了当前子节点的子节点数量。Not using recursion:
Breakdown of the weird part:
tree[i] &&
is used with short-circuit evaluation ensuring thattree[i]
is not null when I calltree[i].children
tree.push.apply(tree, tree[i].childrens);
using apply which allows me to call a function, in this case Array.push, which takes any number of arguments ontree
. So that line basically becomestree.push(child0, child1, ... childn);
.so now
tree.length
has been increased by the number of children on the current child.最简单的解决方案是仅使用基本的递归函数:
其中
parent
的初始值为McDuffFamily
,而visit
是一个可以执行任何操作的函数。当你访问一个节点时想要做的事情。The simplest solution is to just use a basic recursive function:
Where the initial value of
parent
isMcDuffFamily
andvisit
is a function that does whatever you want to do when you visit a node.此函数将返回家谱中给定名称的所有后代:
它将返回一个包含所有后代名称的数组。
PS:我写了
children
而不是childrens
,因为children
已经是复数了。This function will return all the descendants of a given name whitin the family tree:
It will return an array that contains the names of all the descendants.
PS: I wrote
children
instead ofchildrens
, sincechildren
is already plural.如果您使用的环境(例如 Node 或使用 MooTools)允许 [].reduce,您也可以这样做:
我认为 [].reduce 看起来更好,但它更费力
If you are using an environment (like Node or using MooTools) that allows for [].reduce you could also do:
I think [].reduce looks nicer, but it is more taxing