2
let data = {
    "rec": [{
            "id": "25837",
            "contentId": "25838"
        },
        {
            "id": "25839",
            "contentId": "25838"
        },
        {
            "id": "25838"
        },
        {
            "id": "25636",
            "contentId": "25837"
        }, {
            "id": "25640",
            "contentId": "25839"
        }
    ]
};

I have a javascript object which I have to manipulate to below format.

{
    "childern": [{
        "id": "25838",
        "childern": [{
                "id": "25837",
                "contentId": "25838",
                "childern": [{
                    "id": "25636",
                    "contentId": "25837"
                }]
            },
            {
                "id": "25839",
                "contentId": "25838",
                "childern": [{
                    "id": "25640",
                    "contentId": "25839"
                }]
            }
        ]
    }]
}

If any object dont have contentId it should be at parent level. then all the objects having contentId same as parent id should be at its child level and so on.

I have created a fiddle here but logic is not completed. Any idea or reference to achieve this.

1 Answer 1

5

You could create recursive function with reduce method to get the desired result.

let data = {"rec":[{"id":"25837","contentId":"25838"},{"id":"25839","contentId":"25838"},{"id":"25838"},{"id":"25636","contentId":"25837"},{"id":"25640","contentId":"25839"}]}

function nest(data, pid) {
  return data.reduce((r, e) => {
    if (pid == e.contentId) {
      const obj = { ...e }
      const children = nest(data, e.id);
      if (children.length) obj.children = children
      r.push(obj)
    }

    return r;
  }, [])
}

const result = nest(data.rec);
console.log(result[0])

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

Comments

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.