Data format conversion: converting flat arrays to tree json

[
  {source: "001", target: "002", weight: 10},
  {source: "001", target: "003", weight: 15},
  {source: "002", target: "004", weight: 12},
  {source: "004", target: "005", weight: 10},
 ....
]

convert to

[
  {
  id: "001",
  children: [
    {
      id: "002",
      weight: 10,
      children: [
        {
          id: "004",
          weight: 12,
          children: [
            {
              id: "005",
              weight: 10
            }
          ]
        }
      ]
    },
    {
      id: "003",
      weight: 15,
      children: []
    }
   ]
  }
]
Mar.10,2021

build all the trees in a loop, and then find the root node and push it in.

let arr = [...]
let sidMap = {}
let map= {} 
for(let i=0 ;i<arr.length;iPP){
    let pid = arr[i].source
    let sid = arr[i].target
    if(!map[sid]){
        map[sid]={id:sid, children:[]}
    }
    map[sid].weight = arr[i].weight
    if(!map[pid]){
        map[pid]={id:pid, children:[]}
    }
    map[pid].children.push(map[sid])
    sidMap[sid]=true
}
let ans = []
for(let i=0 ;i<arr.length;iPP){
    let pid = arr[i].source
    if(!sidMap[pid]){
        sidMap[pid] = true
        ans.push(map[pid])
    }
}
console.log(ans)

  

two for loops
set an object ob
put all objects of the same source together
and {2: [{.}, {.}],}
the second time for can operate according to the above object
the specific code is not posted

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3c727-2c31f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3c727-2c31f.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?