Collect JSON data

Hello there!

I have a few records in the DB like:

{
 id: 1,
 ref_id: null
}
------
{
 id: 2,
 ref_id: 1
}
------
{
 id: 3,
 ref_id: 1
}
------
{
 id: 4,
 ref_id: 2
}
------
etc...

How i can collect JSON with nested records like:

[
 {
  id: 1,
  ref_id: null,
  childs: [
   {
    id: 2,
    ref_id: 1,
    childs: [
     {
      id: 4,
      ref_id: 2,
      childs: []
     }
    ]
   },
   {
    id: 3,
    ref_id: 1,
    childs: []
   }
  ]
 }
]

I want to render referral tree.
Need your help guys!

ps. sorry for my bad English.
Thanks!

Array to Tree conversion is not about Adonis. It’s more about general JS question.

There are a lot ways to parse flat array to a nested data structure described on stackoverflow and other websites. You can write your own function or you can use package like this one: https://www.npmjs.com/package/array-to-tree

2 Likes

I agree with you. This is where adequate knowledge of vanilla JS comes to play.