I have a JSON structure of nested locations like this: (note, this is pseudo-json, not actual json)
location : "Location Parent"
locationid : 100
parent_location_id: ''
SUBLOCATIONS : Array(2)
location : "Location Child"
locationid : 200
parent_location_id: 100
location : "Location Child Two"
locationid : 300
parent_location_id: 100
location : "Location Parent Two"
locationid : 101
parent_location_id: ''
SUBLOCATIONS : Array(2)
location : "Location Child"
locationid : 201
parent_location_id: 101
location : "Location Child Two"
locationid : 301
parent_location_id: 101
SUBLOCATIONS : Array(2)
location : "Location Sub Child"
locationid : 401
parent_location_id: 301
location : "Location Sub Child Two"
locationid : 501
parent_location_id: 301
I want to be able to recurse through this data and add an attribute to each item that denotes its position or depth in the hierarchy, so in the end, I'll have something like this:
location : "Location Parent"
locationid : 100
parent_location_id : ''
level: 1
SUBLOCATIONS : Array(2)
location : "Location Child"
locationid : 200
parent_location_id : 100
level: 2
location : "Location Child Two"
locationid : 300
parent_location_id : 100
level: 2
location : "Location Parent Two"
locationid : 101
parent_location_id : ''
level: 1
SUBLOCATIONS : Array(2)
location : "Location Child"
locationid : 201
parent_location_id : 101
level: 2
location : "Location Child Two"
locationid : 301
parent_location_id : 101
level: 2
SUBLOCATIONS : Array(2)
location : "Location Sub Child"
locationid : 401
parent_location_id: 301
level: 3
location : "Location Sub Child Two"
locationid : 501
parent_location_id: 301
level: 3
I can recurse through the structure like this:
recursivelyTraverseLocations(locations) {
for (let location of locations) {
if (location.parent_location_id > 0) {
location.level = _depth_
} else {
location.level = 1
}
if (location.SUBLOCATIONS) {
this.recursivelyTraverseLocations(location.SUBLOCATIONS);
}
}
}
But I can't wrap my head around how to initialize and scope the depth variable to count how deep it is in the recursion and reset when it hits the bottom and is starting at the top of a new branch.