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}, [])
相关文章:
