JavaScript 递归对象映射

0 javascript recursion

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

\n\n

源数据:

\n\n
{\n        "id": "41055788",\n        "parent_id": "00000000",\n        "organization": "Consejo Directivo",\n        "level": 1,\n        "children": [\n          {\n            "id": "51cd732c",\n            "parent_id": "41055788",\n            "organization": "Direcci\xc3\xb3n General",\n            "children": [          \n              {\n                "id": "28cd78ff",\n                "parent_id": "51cd732c",\n                "organization": "Direcciones Regionales",\n                "children": []\n                          ....\n
Run Code Online (Sandbox Code Playgroud)\n\n

** 我一直在试图找出如何迭代树和预期结果:**

\n\n
{\n    "data":{\n      "id": "41055788",\n      "parent_id": "00000000",\n      "organization": "Consejo Directivo",\n      "level": 1\n    },\n    "children": [\n      {\n       "data": {\n          "id": "51cd732c",\n        "parent_id": "41055788",\n        "organization": "Direcci\xc3\xb3n General"\n        },\n        "children": [ ] ...\n
Run Code Online (Sandbox Code Playgroud)\n\n

这就是我到目前为止没有成功的事情:

\n\n
**function tranformTransverse(root, tree) {\n        let rmChd = Object.assign({}, root);\n                delete rmChd[\'children\'];\n        this.dataTree.push({\n            data : rmChd,\n            children : (!!root && root.hasOwnProperty("children")) && root[\'children\']\n        });\n\n        if ((!!root && root.hasOwnProperty("children")) && root[\'children\'] instanceof Array)\n            root[\'children\'].forEach(child => {              \n              this.tranformTransverse(child, tree);\n            });\n\n    }**\n
Run Code Online (Sandbox Code Playgroud)\n\n

知道如何实现这个结果吗?

\n

use*_*242 5

只需递归地遍历子级,并使用解构将子级分离出来进行处理,并将其余属性作为新对象放入数据属性中。

\n\n

\r\n
\r\n
data={\r\n  "id": "41055788",\r\n  "parent_id": "00000000",\r\n  "organization": "Consejo Directivo",\r\n  "level": 1,\r\n  "children": [{\r\n    "id": "51cd732c",\r\n    "parent_id": "41055788",\r\n    "organization": "Direcci\xc3\xb3n General",\r\n    "children": [{\r\n      "id": "28cd78ff",\r\n      "parent_id": "51cd732c",\r\n      "organization": "Direcciones Regionales",\r\n      "children": []\r\n    }]\r\n  }]\r\n}\r\n\r\nconst collector = ({children, ...data}) => ({data, children: children.map(collector)})\r\nconsole.log(\r\ncollector(data)\r\n)
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n