Can someone assist me in refactoring a couple of if-statements that are almost identical, but differ only in hierarchy within the currentHierarchie
object? I am looking to consolidate these into a loop or similar construct. The number of if statements should correspond to laneAndAllParentLanesIds.length
.
private createLaneHierarchieStructure(laneAndAllParentLanesIds: any[], currentHierarchie) {
for (let i = 0; i < laneAndAllParentLanesIds.length; i++) {
const obj = currentHierarchie;
const keys = laneAndAllParentLanesIds;
if (i === 0 && !obj[keys[i]])
obj[keys[i]] = {};
if (i === 1 && !obj[keys[i - 1]][keys[i]])
obj[keys[i - 1]][keys[i]] = {};
if (i === 2 && !obj[keys[i - 2]][keys[i - 1]][keys[i]])
obj[keys[i - 2]][keys[i - 1]][keys[i]] = {};
if (i === 3 && !obj[keys[i - 3]][keys[i - 2]][keys[i - 1]][keys[i]])
obj[keys[i - 3]][keys[i - 2]][keys[i - 1]][keys[i]] = {};
if (i === 4 && !obj[keys[i - 4]][keys[i - 3]][keys[i - 2]][keys[i - 1]][keys[i]])
obj[keys[i - 4]][keys[i - 3]][keys[i - 2]][keys[i - 1]][keys[i]] = {};
}
return currentHierarchie;
}
View an example response generated by this code (after invoking it multiple times and storing the results in the same object (currentHierarchie
) using:
for (let i = 0; i < boards.length; i++) {
let laneHierarchie = {};
boards[i]['info']['lanes'].forEach(lane => {
const laneAndAllParentLanesIds = this.getAllParentLanes(i, lane);
laneHierarchie = this.createLaneHierarchieStructure(laneAndAllParentLanesIds, laneHierarchie);
});
console.log(laneHierarchie);
}