将层次结构路径作为数组将树数据转换为平面数据

时间:2018-10-11 19:30:23

标签: javascript angular typescript data-structures

我有以下数据。我需要创建一个层次结构为数组的平面数据结构。如何使用递归函数创建它?

    var tree = [{
    "name": "Firm",
    "id": 1,
    "children": [{
            "name": "veniam",
            "id": 2
        },
        {
            "name": "officia",
            "id": 3
        },
        {
            "name": "ullamco",
            "id": 4
        },
        {
            "name": "duis",
            "id": 5,
            "children": [{
                "name": "aliquip",
                "id": 6,
                "children": [
                    {
                        "name": "culpa",
                        "id": 7
                    },
                    {
                        "name": "qui",
                        "id": 8
                    },
                    {
                        "name": "cillum",
                        "id": 9
                    }
                ]
            }]
        },
        {
            "name": "ullamco",
            "id": 10
        },
    ]
}];

我想要的结果应该是这样。

[{
            "name": "Firm",
            "id": 1,
            "path": [1]
        },
        {
            "name": "veniam",
            "id": 2,
            "path": [1, 2]
        },
        {
            "name": "officia",
            "id": 3,
            "path": [1, 3]
        },
        {
            "name": "ullamco",
            "id": 4,
            "path": [1, 4]
        },
        {
            "name": "duis",
            "id": 5,
            "path": [1, 5]
        },
        {
            "name": "aliquip",
            "id": 6,
            "path": [1, 5, 6]
        },
        ...
        {
            "name": "ullamco",
            "id": 10,
            "path": [1, 10]
        }
    ]  

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以使用reduce方法执行此操作并创建一个递归函数。

var tree = [{"name":"Firm","id":1,"children":[{"name":"veniam","id":2},{"name":"officia","id":3},{"name":"ullamco","id":4},{"name":"duis","id":5,"children":[{"name":"aliquip","id":6,"children":[{"name":"culpa","id":7},{"name":"qui","id":8},{"name":"cillum","id":9}]}]},{"name":"ullamco","id":10}]}]

function flat(data, prev = []) {
  return data.reduce((r, {id, name, children}) => {
    let path = prev.concat(id)
    if(children) r.push(...flat(children, path));
    r.push({name, id, path});
    return r;
  }, [])
}

console.log(flat(tree))

答案 1 :(得分:1)

var tree=[{name:"Firm",id:1,children:[{name:"veniam",id:2},{name:"officia",id:3},{name:"ullamco",id:4},{name:"duis",id:5,children:[{name:"aliquip",id:6,children:[{name:"culpa",id:7},{name:"qui",id:8},{name:"cillum",id:9}]}]},{name:"ullamco",id:10}]}];

function flatten(node, path = [], array = []) {
  const { id, name } = node
  const newPath = [...path, id]
  const children = node.children || []
  array.push({ id, name, path: newPath })
  children.forEach(child => {
    flatten(child, newPath, array)
  })
  return array
}

console.log(flatten(tree[0]))