I am facing an issue with retrieving a tree of terms recursively from a term group using JSOM / JavaScript.
The challenge lies in the fact that all values are being fetched recursively, but the order is completely incorrect.
function recurseTerms(currentTerm, loops){
loops++;
var terms = currentTerm.get_terms();
context.load(terms);
context.executeQueryAsync(
function () {
var termsEnum = terms.getEnumerator();
while (termsEnum.moveNext()) {
var newCurrentTerm = termsEnum.get_current();
termstext += newCurrentTerm.get_name() + "<br>";
//Check if term has child terms.
if (newCurrentTerm.get_termsCount() > 0) {
recurseTerms(newCurrentTerm, loops);
}
}
document.getElementById("resultsDiv").innerHTML = termstext;
},
function () {
//failure to load terms
});
Therefore, when I call the function recurseTerms with the Term-object as the first parameter (root) and 0 for loops (solely for formatting), my hierarchy of terms appears as follows:
Level 1
--Level 1a
--Level 1b
Level 2
Level 3
--Level 3a
----Level 3a
------Level 3a1
------Level 3a2
--------Leve...
However, the actual output generated by the function (termstext) reads:
Level 1
Level 2
Level 3
Level 1a
Level 1b
...
This discrepancy suggests that the function fails to recognize child terms underneath 'Level 1' and struggles to recurse accordingly.
Although I have identified the problem, finding a solution has proven challenging :( Any guidance on the correct approach would be greatly appreciated!