首页 > 解决方案 > 反向遍历层次结构

问题描述

我有一个包含父 ID 的对象层次结构。当我像这样解析 json 对象时,我将 parentId 添加到子对象中。

public static fromJson(json: any): Ancestry | Ancestry[] {
    if (Array.isArray(json)) {
      return  json.map(Ancestry.fromJson) as Ancestry[];
    }

    const result = new Ancestry();
    const { parents } = json;

    parents.forEach(parent => {
      parent.parentId = json.id;
    });

    json.parents = Parent.fromJson(parents);
    Object.assign(result, json);
    return result;
  }

如果我有一个grandchild.id,关于如何拔出祖先的任何想法?

数据在 mockaroo curl ( Ancestry.json )

例如,使用以下 json 和 a grandchild.id = 5,我将使用以下 ID 创建和排列

['5', '0723', '133', '1']

[{
  "id": "1",
  "name": "Deer, spotted",
  "parents": [
    {
      "id": "133",
      "name": "Jaime Coldrick",
      "children": [
        {
          "id": "0723",
          "name": "Ardys Kurten",
          "grandchildren": [
            {
              "id": "384",
              "name": "Madelle Bauman"
            },
            {
              "id": "0576",
              "name": "Pincas Maas"
            },
            {
              "id": "5",
              "name": "Corrie Beacock"
            }
          ]
        },

标签: javascriptarraystypescriptecmascript-5

解决方案


可能有很多方法可以解决这个问题,但在我看来,最简单的方法是简单地在数据结构中进行搜索,并以与找到它们的时间相反的顺序存储 ID。这样输出就是你所追求的。

您也可以只是颠倒不同方法的顺序。

我想指出 json 结构有点奇怪。我原以为它只是有嵌套children数组,而不是将它们重命名为parent,childrengrandchildren.

let data = [{
  "id": "1",
  "name": "Deer, spotted",
  "parents": [
    {
      "id": "133",
      "name": "Jaime Coldrick",
      "children": [
        {
          "id": "0723",
          "name": "Ardys Kurten",
          "grandchildren": [
            {
              "id": "384",
              "name": "Madelle Bauman"
            },
            {
              "id": "0576",
              "name": "Pincas Maas"
            },
            {
              "id": "5",
              "name": "Corrie Beacock"
            }
          ]
        }]
    }]
}]

const expectedResults =  ['5', '0723', '133', '1']

function traverseInverseResults(inputId, childArray) {
    if(!childArray){ return }
    for (const parent of childArray) {
        if(parent.id === inputId){
            return [parent.id]
        } else {
            let res = traverseInverseResults(inputId, parent.parents || parent.children || parent.grandchildren) // This part is a bit hacky, simply to accommodate the strange JSON structure.
            if(res) {
                res.push(parent.id)
                return res
            }
        }
    }
    return
}
let result = traverseInverseResults('5', data)
console.log('results', result)
console.log('Got expected results?', expectedResults.length === result.length && expectedResults.every(function(value, index) { return value === result[index]}))


推荐阅读