Home > Enterprise >  How to push and sort of object array to tree by typescript and javascript?
How to push and sort of object array to tree by typescript and javascript?

Time:10-11

How can I push and sort of object array to a tree by typescript or javascript?

I have 3 object arrays from API like this:

const dataParts = [
  {
    "id": 1,
    "title": "Part 1",
    "chapterID": [11,12],
    "order": 1,
  },
  {
    "id": 2,
    "title": "Part 2",
    "chapterID": [13],
    "order": 2
  }
]

const dataChapters = [
  {
    "id": 11,
    "title": "Chapter 1"
    "criteriasID": [15,16]
    "order": 1,
  },
  {
    "id": 12,
    "title": "Chapter 2",
    "criteriasID": [],
    "order": 2,
  },
  {
    "id": 13,
    "title": "Chapter 1",
    "criteriasID": [],
    "order": 1,
  }
]

const dataCriterias = [
  {
    "id": 15,
    "title": "criteria 1",
    "order": 1,
  },
  {
    "id": 16,
    "title": "criteria 2",
    "order": 2,
  }
]

How can I push element and sort it by "order" properties ?

result I want like this:

const dataTree = [
  {
    "id": 1,
    "title": "Part 1",
    "chapterID": [11,12],
    "order": 1,
    "children": [
        {
          "id": 11,
          "title": "Chapter 1"
          "criteriasID": [15, 16]
          "order": 1,
          "children": [
            {
              "id": 15,
              "title": "criteria 1",
              "order": 1,
            },
            {
              "id": 16,
              "title": "criteria 2",
              "order": 2,
            }
          ]
        },
        {
          "id": 12,
          "title": "Chapter 2",
          "criteriasID": [],
          "order": 2,
          "children": []
        }
      ]
  },
  {
    "id": 2,
    "title": "Part 2",
    "chapterID": [13],
    "order": 2,
    "children": [
        {
          "id": 13,
          "title": "Chapter 1",
          "criteriasID": [],
          "order": 1,
        }
    ]
  }
]

Do you have any idea about this issue? recursive can do this issue? please help me because this is my thesis graduation

Thanks for your help

  • Related