反向遍历层次结构

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

我有一个对象层次结构,其中包含父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;
  }

如果我有孙子孙子,关于如何拔出祖先的任何想法?

数据在模拟袋装(Ancestries.json

作为示例,使用以下json和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"
            }
          ]
        },
javascript arrays typescript ecmascript-5
1个回答
0
投票

也许有很多方法可以解决此问题,但是我认为最简单的方法是简单地在数据结构中进行搜索,并以找到ID时的逆序存储ID。这样,输出就是您想要的。

您还可以颠倒其他方法的顺序。

我想指出json-结构有点怪异。我希望它只是嵌套了children数组,而不是将它们重命名为parentchildrengrandchildren

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]}))
© www.soinside.com 2019 - 2024. All rights reserved.