将带有项目的路径转换为树对象

问题描述 投票:0回答:1

我正在尝试将包含带有项目的路径的对象数组转换为数据树,所以我在路径上写了一个函数路径循环:

从此数组:

[{“ userName”:“ 1”,“标签”:[“ A; B”]},{“ userName”:“ 2”,“标签”:[“ A; B”]},{“ userName”:“ 3”,“标签”:[“ A;”]},{“ userName”:“ 4”,“标签”:[“ A; B; C”]},{“ userName”:“ 5”,“标签”:[“ A; B”]},{“ userName”:“ 6”,“标签”:[“ A; B; C; D”]}]

至此结构:

[{“ name”:“ A”,“家庭”: [{“ name”:“ B”,“家庭”: [{“ name”:“ C”,“家庭”: [{“ name”:“ D”,“家庭”: [],“项目”:[“ 6”]}],“项目”:[“ 4”]}],“项目”:[“ 1”,“ 2”,“ 5”]}],“项目”:[“ 3”]}]

function convertListToTree(associationList) {
    let tree = [];
    for (let i = 0; i < associationList.length; i++) {
        let path = associationList[i].tags[0].split(';');
        let assetName = associationList[i].userName;
        let currentLevel = tree;
        for (let j = 0; j < path.length; j++) {
            let familyName = path[j];
            let existingPath = findWhere(currentLevel, 'name', familyName);
            if (existingPath) {
                if (j === path.length - 1) {
                    existingPath.items.push(assetName);
                }
                currentLevel = existingPath.families;
            } else {
                let assets = [];
                if (j === path.length - 1) {
                    assets.push(assetName)
                }
                let newPart = {
                    name: familyName,
                    families: [],
                    items: assets,
                };
                currentLevel.push(newPart);
                currentLevel = newPart.families;
            }
        }
    }
    return tree;
}

function findWhere(array, key, value) {
    let t = 0;
    while (t < array.length && array[t][key] !== value) {
        t++;
    }
    if (t < array.length) {
        return array[t]
    } else {
        return false;
    }
}

但是我在这里遇到了一些问题,期望的输出与我想要的不一样

[
  {
    "name": "A",
    "families": [
      {
        "name": "B",
        "families": [
          {
            "name": "C",
            "families": [
              {
                "name": "D",
                "families": [],
                "items": [
                  "6"
                ]
              }
            ],
            "items": [
              "4"
            ]
          }
        ],
        "items": [
          "1",
          "2",
          "5"
        ]
      },
      {
        "name": "",
        "families": [],
        "items": [
          "3"
        ]
      }
    ],
    "items": []
  }
]

[有人可以帮我解决这个问题

javascript node.js json ramda.js
1个回答
0
投票

您应该能够使用递归来实现这一点,通过在每个级别调用getFamilies和getUsers函数:

© www.soinside.com 2019 - 2024. All rights reserved.