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?
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].childrentree.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.lengthhas been increased by the number of children on the current child.