You could use the parents
property of the node object you get from data.instance.get_node()
. As several nodes could have the same ancestor, you'd maybe want to avoid gathering duplicates. For this you can use a Set
. This is just one way you could do it:
var nodesOnSelectedPath = [...data.selected.reduce(function (acc, nodeId) {
var node = data.instance.get_node(nodeId);
return new Set([...acc, ...node.parents, node.id]);
}, new Set)];
console.log('Selected: ' + nodesOnSelectedPath.join(', '));
Note that this will include the root node as well, which has id '#'.
Here is the updated fiddle.
Without the root node
To get the list without the #
, it is the easiest to apply a filter on the result:
console.log('Selected: ' + nodesOnSelectedPath.filter(id => id !== '#').join(', '));
EcmaScript2015
The above scripts use features from EcmaScript2015 (ES6). Some editors may highlight syntax errors when they are not configured to recognise ES6 syntax. Here you can find how to configure VSCode, Sublime Text, and WebStorm for ES6.
ES5 Alternative
In ES5 you would use an object (acc
) to collect unique id references as property names. Although Object.keys
is really ES6, it is often supported in otherwise ES5 browsers:
var nodesOnSelectedPath = Object.keys(data.selected.reduce(function (acc, nodeId) {
var node = data.instance.get_node(nodeId);
node.parents.forEach(function (id) {
acc[id] = 1;
});
acc[node.id] = 1;
return acc;
}, {}));
Here is the corresponding fiddle.
Circular references in data
You wrote in comments that you tried to do this:
JSON.stringify(data)
But that data structure has parent and child references in it, so it is possible to go from a child to its parent object, and from there back to its child object, ... which is endless. Such structures cannot be converted to JSON. See this Q&A for solutions.