Jaydeep
Jaydeep

Reputation: 1716

Modify javascript object to specific format

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.

Upvotes: 2

Views: 111

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122027

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

Upvotes: 5

Related Questions