-1

what i have is a single level array of objects

data = [ 
  {"id": 1, "catTitle": "Item1", "parentId": null },
  {"id": 2, "catTitle": "Item2", "parentId": null },
  {"id": 3, "catTitle": "Item3", "parentId": null },
  {"id": 4, "catTitle": "Item4", "parentId": 1 },
  {"id": 5, "catTitle": "Item5", "parentId": 1 },
  {"id": 6, "catTitle": "Item6", "parentId": 2 },
  {"id": 7, "catTitle": "Item7", "parentId": 2 },
  {"id": 8, "catTitle": "Item8", "parentId": 3 },
  {"id": 9, "catTitle": "Item9", "parentId": 5 },
  {"id": 10, "catTitle": "Item10", "parentId": 5 },
  {"id": 11, "catTitle": "Item11", "parentId": 7 },
  {"id": 12, "catTitle": "Item12", "parentId": 10 },
]

what i want is to convert the array into an array of objects with parent-child kind of relationship. Here the parentId of an item refers to the id of the parent item.

result = [
  {
    "id": 1,
    "catTitle": "Item1",
    "parentId": null,
    "childs": [{
        "id": 4,
        "catTitle": "Item4",
        "parentId": 1,
        "childs": []
      },
      {
        "id": 5,
        "catTitle": "Item5",
        "parentId": 1,
        "childs": [{
            "id": 9,
            "catTitle": "Item9",
            "parentId": 5
          },
          {
            "id": 10,
            "catTitle": "Item10",
            "parentId": 5,
            "childs": [{
              "id": 12,
              "catTitle": "Item12",
              "parentId": 10
            }]
          },
        ]
      },
    ]
  },
  .
  .
  .
]
1

1 Answer 1

0

const data = [ 
  {"id": 1, "catTitle": "Item1", "parentId": null },
  {"id": 2, "catTitle": "Item2", "parentId": null },
  {"id": 3, "catTitle": "Item3", "parentId": null },
  {"id": 4, "catTitle": "Item4", "parentId": 1 },
  {"id": 5, "catTitle": "Item5", "parentId": 1 },
  {"id": 6, "catTitle": "Item6", "parentId": 2 },
  {"id": 7, "catTitle": "Item7", "parentId": 2 },
  {"id": 8, "catTitle": "Item8", "parentId": 3 },
  {"id": 9, "catTitle": "Item9", "parentId": 5 },
  {"id": 10, "catTitle": "Item10", "parentId": 5 },
  {"id": 11, "catTitle": "Item11", "parentId": 7 },
  {"id": 12, "catTitle": "Item12", "parentId": 10 },
]

const result = data.filter(item => item.parentId === null)

const queue = [...result]

while(queue.length) {
  const item = queue.shift()
  item.children = data.filter(i => i.parentId === item.id)
  queue.push(...item.children)
}

console.log(result)

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.