如何将平面数据结构转换为树状结构?

时间:2018-11-08 15:05:53

标签: javascript arrays algorithm object

假设我有两个辅助函数,将{}的平面数组转换为树状结构。考虑以下平面数据:

const data = [
     {
            "ID": 1,
            "Tier_1": "DataSource1",
            "Tier_2": "Area",
            "Tier_3": "General",
        },
        {
            "ID": 2,
            "Tier_1": "DataSource1",
            "Tier_2": "Financial",
            "Tier_3": "General",
        },
        {
            "ID": 3,
            "Tier_1": "DataSource1",
            "Tier_2": "Area",
            "Tier_3": "General",
        },
        {
            "ID": 4,
            "Tier_1": "DataSource2",
            "Tier_2": "Area",
            "Tier_3": "General",
        },
        {
            "ID": 5,
            "Tier_1": "DataSource2",
            "Tier_2": "Area",
            "Tier_3": "Management Plan",
        }
]

数据包含三行某些层次结构的信息,我希望将其转换为树状结构,如下所示(预期输出):

(最后一个子级是实际的数据库对象,但分布在树上)

const output = {
  "DataSource1: {
    "Area": {
        {
            "ID": 1,
            "Tier_1": "DataSource1",
            "Tier_2": "Area",
            "Tier_3": "General",
        },
        {
            "ID": 3,
            "Tier_1": "DataSource1",
            "Tier_2": "Area",
            "Tier_3": "General",
        },
      },
      "Financial": [
        {
            "ID": 2,
            "Tier_1": "DataSource1",
            "Tier_2": "Financial",
            "Tier_3": "General",
        },
      ]
  },
  "DataSource2: {
      "Area": [
          {
            "ID": 4,
            "Tier_1": "DataSource2",
            "Tier_2": "Area",
            "Tier_3": "General",
          },
          {
            "ID": 5,
            "Tier_1": "DataSource2",
            "Tier_2": "Area",
            "Tier_3": "Management Plan",
          }
       ]
      }
  }
}

我实际上设法创建了函数来完成此任务,但是我不太灵活(深度/暗淡是固定的,在每个函数名称中都有说明)

返回二维树的函数:

const getDataCategoriesTwoDim = (data, mainCategory) => {
  const dataFields = [...data];
  let map = {};

  for (let i = 0; i < dataFields.length; i += 1) {
    const currentField = dataFields[i];
    const currentCategory = currentField[mainCategory];

    if (!map[currentCategory]) {
      map[currentCategory] = [];
    }
    map[currentCategory].push(currentField);
  }

  return map;
};

函数返回三维树:

const getDataCategoriesThreeDim = (data, mainCategory, subCategory) => { // DIFF
  const dataFields = [...data];
  let map = {};

  for (let i = 0; i < dataFields.length; i += 1) {
    const currentField = dataFields[i];
    const currentCategory = currentField[mainCategory];
    const currentSubcategory = currentField[subCategory]; // DIFF

    if (!map[currentCategory]) {
      map[currentCategory] = {}; /DIFF
    }
    if (!map[currentCategory][currentSubcategory]) { // DIFF
      map[currentCategory][currentSubcategory] = []; // DIFF
    } // DIFF
    map[currentCategory][currentSubcategory].push(currentField); // DIFF
  }

  return map;
};

您可以像这样调用两者并获得预期结果:

  getDataCategoriesTwoDim(data, 'Tier_2');
  getDataCategoriesThreeDim(data, 'Tier_2', 'Tier_3');

如您所见,有太多的代码重复和复制粘贴。我在评论中标记了差异。如何将代码重写为一个函数,以便设置2、3或更大的尺寸?

1 个答案:

答案 0 :(得分:3)

您可以使用用于嵌套属性的键,并为最后一个键而不是对象添加数组。稍后将对象推送到嵌套数组。

const
    groupBy = (data, keys) => data.reduce((r, o) => {
        keys
            .reduce((p, k, i, a) =>
                 p[o[k]] = p[o[k]] || (i + 1 === a.length ? [] : {}), r)
            .push(o);
        return r;
    }, Object.create(null)),
    data = [{ ID: 1, Tier_1: "DataSource1", Tier_2: "Area", Tier_3: "General" }, { ID: 2, Tier_1: "DataSource1", Tier_2: "Financial", Tier_3: "General" }, { ID: 3, Tier_1: "DataSource1", Tier_2: "Area", Tier_3: "General" }, { ID: 4, Tier_1: "DataSource2", Tier_2: "Area", Tier_3: "General" }, { ID: 5, Tier_1: "DataSource2", Tier_2: "Area", Tier_3: "Management Plan" }],
    result1 = groupBy(data, ["Tier_1", "Tier_2"]),
    result2 = groupBy(data, ["Tier_1", "Tier_2", "Tier_3"]);

console.log(result1);
console.log(result2);
.as-console-wrapper { max-height: 100% !important; top: 0; }