I have a collection of objects in TypeScript. Each object has a method called getSubObjects
which returns a collection of objects of the same type containing the same method getSubObjects
. My requirement is
- Have to iterate through the original collection calling
getSubObjects
of each object in the collection. - For each object returned call
getSubObjects
again. - Keep on going for each object returned until there is no object
So in my loop I want to do something like the following
objCol.forEach(item => {
const col = item.getSubObjects();
if(col){
objCol.pushRange(col)
}
});
I don't think this is possible in TypeScript, the only alternative I can think of is to resort to recursion, but I would rather avoid it if there an alternative way in which I can do this.
You can avoid recursion by using a naive loop like the following (I did not run the [pseudo] code myself though):
First add another boolean property
processed
to each object, initializedfalse
. Then: