Search code examples
javascripttypescriptindexingnestedjavascript-objects

How can i access/create nested objects dynamically (go deeper based on a number in a loop)


I have a couple of if-statements that do almost exactly the same, just one hierarchy deeper on the currentHierarchie object. Can anyone help me put this in a loop (or something). The amount of if statements this way must be the same as 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;
}

example response of this code (after calling it multiple times and saving it to the same object (currentHierarchie) like:

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);
}

Solution

  • You could move the obj variable declaration and initialization outside of the for loop and take only a single value as key for checking obj and assign an empty array if necessary.

    Then assign the last property to obj for the next loop.

    const obj = currentHierarchie;
    
    for (let key of laneAndAllParentLanesIds) {
        obj[key] = obj[key] || {};
        obj = obj[key];
    }
    

    A version with reduce

    void laneAndAllParentLanesIds.reduce((o, id) => o[id] = o[id] || {}, currentHierarchie);