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 somet...

问题:

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

回答1:

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);
  • 发表于 2018-07-14 00:50
  • 阅读 ( 281 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除