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?

1

1 Answer 1

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)
)

Sign up to request clarification or add additional context in comments.

2 Comments

nice answer! in this particular case, you can write ... => ({ data, children: children.map(collector) })
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%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.