从树结构创建节点结构

时间:2019-07-24 20:52:05

标签: typescript

我目前具有这样的结构

{

    "A1": {
        "B1": {
            "C1": {},
            "C2": {}
        },
        "B2": {
            "C2": {}
        }
    },
    "A2": {}
}

我想要这样的东西

[

 {
   name: A1,
   child:[ {
            name: B1,
            child:[
                    {
                        name: C1,
                        child:[]
                    },
                    {
                        name: C2,
                        child:[]
                    }
                ]
            },
            {
            name: B2,
            child:[
                    {
                        name: C1,
                        child:[]
                    },
                    {
                        name: C2,
                        child:[]
                    }
                ]
            }
        ]
 },
 {
   name: A1,
   child:[] 
 }
]

1 个答案:

答案 0 :(得分:1)

您可以使用Object.entries()定义一个递归函数,以映射树中每个子结构的键/值对:

const myTree = {
  A1: {
    B1: {
      C1: {},
      C2: {}
    },
    B2: {
      C2: {}
    }
  },
  A2: {}
};

function treeToNode (tree) {
  return Object.entries(tree).map(
    ([key, value]) => ({
      name: key,
      child: treeToNode(value)
    })
  );
}

console.log(treeToNode(myTree));

基于your previous question,如果您想跳过生成树的中间步骤,则可以使用扩展Map的辅助类将定界字符串数组直接转换为节点: / p>

const myHierarchy = [
  'house.bedroom.bed',
  'house.kitchen.spoon',
  'house.kitchen.knife',
  'house.bedroom.sofa',
  'house.bedroom.tv',
  'neighbor.house',
  'plants.trees',
  'house.birds.parrot.grey'
];

class NodeMap extends Map {
  static fromHierarchy (hierarchy) {
    return hierarchy.reduce(
      (node, id) => (
        id.split('.').reduce(
          (node, key) => node.add(key),
          node
        ),
        node
      ),
      new NodeMap()
    );
  }

  add (key) {
    const value = this.get(key) || new NodeMap();
    this.set(key, value);
    return value;
  }

  search (id) {
    return Array.from(this).flatMap(
      ([key, value]) => [
        ...(key === id ? [key] : []),
        ...value.search(id).map(
          rest => [key, rest].join('.')
        )
      ]
    );
  }

  toJSON () {
    return Array.from(this).map(
      ([key, value]) => ({
        name: key,
        child: value
      })
    );
  }
}

const myNode = NodeMap.fromHierarchy(myHierarchy);

console.log(myNode.search('knife'));
console.log(myNode.search('birds'));
console.log(myNode.search('house'));
console.log(myNode.search('flowers'));
console.log(myNode);

search()返回结果数组,以防存在多个匹配项,例如示例中的house