0

我有点坚持递归映射对象,这是源对象:

源数据:

{
        "id": "41055788",
        "parent_id": "00000000",
        "organization": "Consejo Directivo",
        "level": 1,
        "children": [
          {
            "id": "51cd732c",
            "parent_id": "41055788",
            "organization": "Dirección General",
            "children": [          
              {
                "id": "28cd78ff",
                "parent_id": "51cd732c",
                "organization": "Direcciones Regionales",
                "children": []
                          ....

**我一直在试图弄清楚如何遍历树和预期的结果:**

{
    "data":{
      "id": "41055788",
      "parent_id": "00000000",
      "organization": "Consejo Directivo",
      "level": 1
    },
    "children": [
      {
       "data": {
          "id": "51cd732c",
        "parent_id": "41055788",
        "organization": "Dirección General"
        },
        "children": [ ] ...

这就是我到现在为止没有成功的事情:

**function tranformTransverse(root, tree) {
        let rmChd = Object.assign({}, root);
                delete rmChd['children'];
        this.dataTree.push({
            data : rmChd,
            children : (!!root && root.hasOwnProperty("children")) && root['children']
        });

        if ((!!root && root.hasOwnProperty("children")) && root['children'] instanceof Array)
            root['children'].forEach(child => {              
              this.tranformTransverse(child, tree);
            });

    }**

任何想法如何达到这个结果?

4

1 回答 1

3

只是递归地走孩子,并使用解构将孩子分离出来进行处理,并将其余属性作为新对象放在 data 属性中。

data={
  "id": "41055788",
  "parent_id": "00000000",
  "organization": "Consejo Directivo",
  "level": 1,
  "children": [{
    "id": "51cd732c",
    "parent_id": "41055788",
    "organization": "Dirección General",
    "children": [{
      "id": "28cd78ff",
      "parent_id": "51cd732c",
      "organization": "Direcciones Regionales",
      "children": []
    }]
  }]
}

const collector = ({children, ...data}) => ({data, children: children.map(collector)})
console.log(
collector(data)
)

于 2020-05-24T03:33:20.090 回答