I have javascript array, where each item has reference to parent, and they can be looped (circular reference). Example:
[
{"id": 1, "firstName": "Macko","parentId": 12},
{"id": 2, "firstName": "Jess","parentId": 1},
{"id": 3, "firstName": "Peter","parentId": 1},
{"id": 4, "firstName": "Lisa", "parentId": 1},
{"id": 5, "firstName": "Megan","parentId": 1},
{"id": 6, "firstName": "John", "parentId": 4},
{"id": 7, "firstName": "Joe", "parentId": 4},
{"id": 8, "firstName": "Matthew","parentId": 2},
{"id": 9, "firstName": "Peter","parentId": 2},
{"id": 10, "firstName": "Dio","parentId": 5},
{"id": 11, "firstName": "Hello","parentId": 5},
{"id": 12, "firstName": "Ana", "parentId": 4}
]
I needed to create nested data structure based on selected record to display it in the DOM, which I achieved by recursive function like below (source here)
function getNestedChildren(arr, parent) {
var out = []
for(var i in arr) {
if(arr[i].parent == parent) {
var children = getNestedChildren(arr, arr[i].id)
if(children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
It works really well, but not for circular data structures. The thing is I need to stop function execution before it reaches to element from which it started.
How can I achieve this?