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. 问题Unknown column ’’ in ’where clause’2. angular.js - 如何控制ngrepeat输出的个数3. html - vue项目中用到了elementUI问题4. javascript - 在使用 vue.js element ui的时候 怎么样保留table翻页后check的值?5. mysql_replication - mysql读写分离时如果单台写库也无法满足性能怎么解决6. javascript - vue组件通过eventBus通信时,报错a.$on is not a function7. css3 - css怎么实现图片环绕的效果8. linux - ubuntu 命令行中文 显示菱形,期望通过引入字体解决而不是zhcon这种方式9. ionic 项目 ionic build android -release 打包时报错10. python - 如何用pandas处理分钟数据变成小时线?

网公网安备