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

Menu