Let's say I have a nested object like so:
{
label: 'parent',
eyeColor: 'brown',
kids: [
{
label: 'kid_0',
eyeColor: 'brown',
kids: [
{
label: 'kid_0_0',
eyeColor: 'green',
kids: []
},
{
label: 'kid_0_1',
eyeColor: 'brown',
kids: [
{
label: 'kid_0_1_0',
eyeColor: 'brown',
kids: []
}
]
}
],
},
{
label: 'kid_1',
eyeColor: 'brown',
kids: [
{
label: 'kid_1_0',
eyeColor: 'brown',
kids: []
}
],
},
{
label: 'kid_2',
eyeColor: 'green',
kids: []
}
]
};
If I wanted to store all unique paths, how would I do so recursively? I've tried many attempts, but I can't seem to obtain unique paths (my paths build on top of previous paths).
So my expected output would be:
[
['parent', 'kid_0', 'kid_0_0],
['parent', 'kid_0', 'kid_0_1, kid_0_1_0],
['parent', 'kid_1', 'kid_1_0],
['parent', 'kid_2]
]
But if I wanted to stop the path when I found a kid or node with an eyeColor
other than brown
, the path would stop there. Then what would have to change to obtain the following:
[
['parent', 'kid_0', 'kid_0_1, kid_0_1_0],
['parent', 'kid_1', 'kid_1_0],
]
This is my current code, which is now error-ing out b/c of maximum call stack.
var printPaths = function(node, color) {
var paths = [];
var trackPath = function(obj, feature, path) {
if (obj.eyeColor === 'brown') {
path.push(node.label);
} else if (obj.eyeColor !== 'brown') {
paths.push(path);
} else if (obj.kids.length === 0) {
paths.push(path);
}
for (var i = 0; i < obj.kids.length; i++) {
trackPath(obj.kids[i], feature, path)
path.pop();
}
};
trackPath(node, color, []);
return paths;
}