Reputation: 5930
I have an array of objects like this:
[{
name: "Peter",
childs: [{
name: "John",
childs: [{
name: "Joseph",
childs: []
}]
}]
},
{
name: "Carl",
childs: [{
name: "Sam",
childs: []
}]
}]
Where each person can have children and each of these children can have any number of children and so on. Does anyone know a good way to perform this on underscore.js
?
Upvotes: 1
Views: 1853
Reputation: 6802
It seems like you're asking how to do tree traversal, but not anything unique to underscore.js. You can do a depth first traversal this way:
var children = [{name: "Peter", childs: [...]}, ...]
function traverseAndPrint(tree) {
for (var i = 0; i < tree.length; i++) {
console.log(tree[i].name);
traverseAndPrint(tree[i].childs);
}
}
If you need to perform an arbitrary action on each element, you could do the following:
function traverseAndCallFunction(tree, functionToCall) {
for (var i = 0; i < tree.length; i++) {
functionToCall(tree[i]);
traverseAndPrint(tree[i].childs);
}
}
where functionToCall
is a function that takes a child object (according to your example)
I don't see why you'd need underscore.js to do tree traversal.
Upvotes: 3
Reputation: 48761
Sorry, I don't know how specifically in underscore, but it seems a simple recursive function would be easy enough for you.
var data = [{
name: "Peter",
childs: [{
name: "John",
childs: [{
name: "Joseph",
childs: []
}]
}, {
name: "Carl",
childs: [{
name: "Sam",
childs: []
}]
}]
}];
function trav(data, fn) {
data.forEach(function(item) {
for (var p in item)
if (p === "childs")
trav(item[p], fn);
else
fn(item[p], p);
});
}
trav(data, function(val, prop) {
console.log(prop, val);
});
Upvotes: 1