javascript - js寫一個遞歸把數據結構重組成另外的結構
問題描述
現在有以下數據結構:
[{ id: 1, pid: 0, name: '年級'}, { id: 2, pid: 1, name: '一年級'}, { id: 3, pid: 1, name: '二年級'}, { id: 4, pid: 0, name: '專業'}, { id: 5, pid: 4, name: '單片機開發'}]
寫一個JS方法,將其轉換成以下格式數據:
[{ id: 1, pid: 0, name: '年級', children: [{id: 2,pid: 1,name: '一年級' }, {id: 3,pid: 1,name: '二年級' }]}, { id: 4, pid: 0, name: '專業', children: [{id: 5,pid: 4,name: '單片機開發' }]}]
問題解答
回答1:var list = [{ id: 1, pid: 0, name: '年級'}, { id: 2, pid: 1, name: '一年級'}, { id: 3, pid: 1, name: '二年級'}, { id: 4, pid: 0, name: '專業'}, { id: 5, pid: 4, name: '單片機開發'}];function parseList (list) { var map = {}; list.forEach(function (item) {if (!map[item.id]) { map[item.id] = item; } }); list.forEach(function (item) {if (item.pid != 0) { map[item.pid].chidren ? map[item.pid].chidren.push(item) : map[item.pid].chidren = [item];} }); return list.filter(function (item) {return item.pid === 0; });}var newList = parseList(list);回答2:
var list = [ { id: 1, pid: 0, name: '年級' }, { id: 2, pid: 1, name: '一年級' }, { id: 3, pid: 1, name: '二年級' }, { id: 4, pid: 0, name: '專業' }, { id: 5, pid: 4, name: '單片機開發' }];// 生成查找表,可以按 id 查到節點const dict = list.reduce((all, item) => { all[item.id] = item; return all;}, {});// 由于原始數據沒有 id 為 0 的根節點,// 這里模擬一個,最終它的 children 就是實際的所有根節點var root = { id: 0};dict[0] = root;// 循環添加關系list.forEach(item => { const parent = dict[item.pid]; // 確保父節點的 children 存在 parent.children = parent.children || []; parent.children.push(item);});// 輸出結果 root.children// 注意,root 不是結果,root.children 才是console.log(JSON.stringify(root.children, null, 4));
參考一下
var sortedData = data.reduce((result, item) => { result[item.id] = Object.assign({}, item) return result}, [])var result = sortedData.reduce((result, item) => { if (item.pid === 0) { result.push(item) } else { if (sortedData[item.pid].children) { sortedData[item.pid].children.push(item) } else { sortedData[item.pid].children = [item] } } return result}, [])
相關文章:
1. Docker for Mac 創建的dnsmasq容器連不上/不工作的問題2. javascript - 求賜教:網易郵箱Web端模擬登錄看信的加密參數_ntes_nnid、_ntes_nuid3. javascript - 使用angular 的ui-sref 中出現了中文參數,點擊跳轉后瀏覽器的地址欄里出現轉義后的%AE....%a%44. java - ConcurrentHashMap中的get()方法為什么可以不加鎖?5. javascript - QWebEngineView 如何爬 angular 的動態數據?6. html5 - 這個代碼顯示功能如何實現?7. javascript - 用JS 七牛上傳圖片出現文件已存在的錯誤(file exists)8. 工作近5年,3年Java Web ,近2年前端,未來何去何從?9. css3 - 圖片等比例縮放10. java - 字節流轉成字符串之后,在通過字符串轉成字節流后的文件為什么會不一樣?
