在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 數(shù)據(jù)格式轉(zhuǎn)換:扁平數(shù)組轉(zhuǎn)換為樹狀json

數(shù)據(jù)格式轉(zhuǎn)換:扁平數(shù)組轉(zhuǎn)換為樹狀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},
 ....
]

轉(zhuǎn)換為

[
  {
  id: '001',
  children: [
    {
      id: '002',
      weight: 10,
      children: [
        {
          id: '004',
          weight: 12,
          children: [
            {
              id: '005',
              weight: 10
            }
          ]
        }
      ]
    },
    {
      id: '003',
      weight: 15,
      children: []
    }
   ]
  }
]
回答
編輯回答
孤島

一次循環(huán)構(gòu)建所有的數(shù)樹, 然后把根節(jié)點找到push進去就好了

let arr = [...]
let sidMap = {}
let map= {} 
for(let i=0 ;i<arr.length;i++){
    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;i++){
    let pid = arr[i].source
    if(!sidMap[pid]){
        sidMap[pid] = true
        ans.push(map[pid])
    }
}
console.log(ans)
2018年3月4日 05:50
編輯回答
哎呦喂

兩次 for循環(huán)
設(shè)置一個 對象ob
第一次 把相同 source 的 對象都 放在一起
及 {2: [{...},{...}],}
第二次 for 就可以 根據(jù)上面的 對象 來 進行操作
具體代碼不貼了

2017年8月7日 05:00
編輯回答
赱丅呿
const arrays = [
  {source: '001', target: '002', weight: 10},
  {source: '001', target: '003', weight: 15},
  {source: '002', target: '004', weight: 12},
  {source: '004', target: '005', weight: 10}
]

let tree = [];


const genTree = (tree = [], arr) => {
  if (tree.length === 0) {
    return tree.concat(arr);
  }
  if (tree.some(t => t.target === arr.source)) {
    return tree.map(t => {
      if(t.target === arr.source) {
        if (t.children) {
          t.children.concat([arr]);
        } else {
          t.children = [arr];
        }
      }
      return t;
    });
  } else {
    if(tree.some(t => t.hasOwnProperty('children'))) {
      return tree.map(t => {
        if (t.hasOwnProperty('children')) {
          t.children.concat(genTree(t.children, arr));
        }
        return t;
      });
    }
    return tree.concat(arr);
  }
};


arrays.forEach(arr => {
  tree = genTree(tree, arr);
  // console.log(tree)
})

console.log(tree);

結(jié)果:
圖片描述

2017年10月15日 23:04