0

I have a JSON structure which consists of a flat array like below, It is a list of blocks which can have nested child blocks, But in the flat array it only mentions the ids of its children

[
  {
    "id": "1",
    "type": "p",
    "blocks": ["3","4","5"]
  },
  {
    "id": "2",
    "type": "h1",
    "blocks": ["6","7", "9"]
  },
  {
    "id": "3",
    "type": "p",
    "blocks": ["8"]
  },
  {
    "id": "4",
    "type":"p",
    "blocks": ["10"]
  },
  {
    "id": "5",
    "type":"p",
    "blocks": [{"text": "some text"}]
  },
  {
    "id": "6",
    "type":"p",
    "blocks": [{"text": "some more text"}]
  },
  {
    "id": "7",
    "type":"p",
    "blocks": [{"text": "some more text in id 7"}]
  },
  {
    "id": "8",
    "type":"p",
    "blocks": [{"text": "some more text in id 8"}]
  },
  {
    "id": "9",
    "type":"p",
    "blocks": [{"text": "some more text in id 9"}]
  },
  {
    "id": "9",
    "type":"p",
    "blocks": [{"text": "some more text in id 10"}]
  }
]

I want to convert the above flat array into a recursively nested structure which looks like this in which I want to replace the block ids with the actual blocks:

   [
      {
        "id": "1",
        "type": "p",
        "blocks": [
          {
            "id": "3",
            "type": "p",
            "blocks": [
              {
                "id": "8",
                "type": "p",
                "blocks": [
                  {
                    "text": "some more text in id 8"
                  }
                ]
              }
            ]
          },
          {
            "id": "4",
            "type": "p",
            "blocks": [
              {
                "id": "10",
                "type": "p",
                "blocks": [
                  {
                    "text": "some more text in id 10"
                  }
                ]
              }
            ]
          },
          {
            "id": "5",
            "type": "p",
            "blocks": [
              {
                "text": "some text"
              }
            ]
          }
        ]
      },
      {
        "id": "2",
        "type": "h1",
        "blocks": [
          {
            "id": "6",
            "type": "p",
            "blocks": [
              {
                "text": "some more text"
              }
            ]
          },
          {
            "id": "7",
            "type": "p",
            "blocks": [
              {
                "text": "some more text in id 7"
              }
            ]
          },
          {
            "id": "9",
            "type": "p",
            "blocks": [
              {
                "text": "some more text in id 9"
              }
            ]
          }
        ]
      }
    ]
Rohan Keskar18
  • 193
  • 1
  • 10

0 Answers0