javascript - js寫一個遞歸把數(shù)據(jù)結(jié)構(gòu)重組成另外的結(jié)構(gòu)
問題描述
現(xiàn)在有以下數(shù)據(jù)結(jié)構(gòu):
[{ id: 1, pid: 0, name: '年級'}, { id: 2, pid: 1, name: '一年級'}, { id: 3, pid: 1, name: '二年級'}, { id: 4, pid: 0, name: '專業(yè)'}, { id: 5, pid: 4, name: '單片機(jī)開發(fā)'}]
寫一個JS方法,將其轉(zhuǎn)換成以下格式數(shù)據(jù):
[{ id: 1, pid: 0, name: '年級', children: [{id: 2,pid: 1,name: '一年級' }, {id: 3,pid: 1,name: '二年級' }]}, { id: 4, pid: 0, name: '專業(yè)', children: [{id: 5,pid: 4,name: '單片機(jī)開發(fā)' }]}]
問題解答
回答1:var list = [{ id: 1, pid: 0, name: '年級'}, { id: 2, pid: 1, name: '一年級'}, { id: 3, pid: 1, name: '二年級'}, { id: 4, pid: 0, name: '專業(yè)'}, { id: 5, pid: 4, name: '單片機(jī)開發(fā)'}];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: '專業(yè)' }, { id: 5, pid: 4, name: '單片機(jī)開發(fā)' }];// 生成查找表,可以按 id 查到節(jié)點const dict = list.reduce((all, item) => { all[item.id] = item; return all;}, {});// 由于原始數(shù)據(jù)沒有 id 為 0 的根節(jié)點,// 這里模擬一個,最終它的 children 就是實際的所有根節(jié)點var root = { id: 0};dict[0] = root;// 循環(huán)添加關(guān)系list.forEach(item => { const parent = dict[item.pid]; // 確保父節(jié)點的 children 存在 parent.children = parent.children || []; parent.children.push(item);});// 輸出結(jié)果 root.children// 注意,root 不是結(jié)果,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}, [])
相關(guān)文章:
1. javascript - 微信網(wǎng)頁開發(fā)從菜單進(jìn)入頁面后,按返回鍵沒有關(guān)閉瀏覽器而是刷新當(dāng)前頁面,求解決?2. 視頻文件不能播放,怎么辦?3. mysql - 分庫分表、分區(qū)、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處4. mysql - jdbc的問題5. node.js - nodejs開發(fā)中常用的連接mysql的庫6. mysql replace 死鎖7. mysql - 把一個表中的數(shù)據(jù)count更新到另一個表里?8. mysql - 如何減少使用或者不用LEFT JOIN查詢?9. 老師您的微信號是多少?10. mysql - 字符串根據(jù)字典替換
