Get All Children Names From Object
How can I get all names from this object? var familyTree = {name: 'Alex', children:[ {name: 'Ricky', children:'[...]'} {name: 'John',
Solution 1:
You could write a simple recursive function that will traverse the contents of your tree:
var familyTree = {
name: 'Alex',
children: [
{
name: 'Ricky',
children: [ ]
},
{
name: 'John',
children: [
{
name: 'Tom',
children: [ ]
}
]
}
]
};
var traverse = function(tree) {
console.log(tree.name);
for (var i = 0; i < tree.children.length; i++) {
traverse(tree.children[i]);
}
};
traverse(familyTree);
Solution 2:
For the more flexible case where you want to return an array instead of just logging to console, here is another approach that recursively accumulates an array with depth-first traversal and argument passing:
function storeNames(tree, names) {
(names = names || []).push(tree.name);
for(var i = 0; i < tree.children.length; i++) {
storeNames(tree.children[i], names);
}
return names;
}
Here's another approach that's written in more of a functional style:
function storeNames(tree) {
return Array.prototype.concat(tree.name,
tree.children.map(function(child) {
return storeNames(child);
}).reduce(function(flattenedArr, nestedArr) {
return flattenedArr.concat(nestedArr);
})
);
}
Post a Comment for "Get All Children Names From Object"