0

Im little bit stuck on mapping an object recursively, this is the source object :

source 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": []
                          ....

** I've been trying to figure out how to iterate through the tree and result expected:**

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

this is what im on till now without success:

**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);
            });

    }**

Any Idea how to achieve this result?

Pashenkov
  • 3
  • 2
  • Does this answer your question? [looping through an object (tree) recursively](https://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively) – kmoser May 24 '20 at 02:25

1 Answers1

5

Just recusively walk children, and uses destructuring to separate children out for processing, and place the rest of the properties in the data property as a new object.

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)
)
user120242
  • 14,918
  • 3
  • 38
  • 52
  • 1
    nice answer! in this particular case, you can write `... => ({ data, children: children.map(collector) })` – Mulan May 24 '20 at 04:52
  • this works like a charm, i was about shot me in the face, thanks god working in collaboration really hits in the nail. thanks for the help... solution 100% – Pashenkov May 24 '20 at 15:10