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. css3 - 纯CSS实现宽度是百分比的元素成为一个正方形,适配各种屏幕?2. python - django在nginx里模板输出html标签问题3. angular.js - angular如何获取一段html代码赋值到另一个地方,html里面的ng-click事件还要能生效?4. nginx - 使用wordpress搭建博客,怎么实现真实服务器使用HTTP,然后使用UPYUN的HTTPS加密?5. 我想从Java Date中获取Year,Month,Day等,以便与Java中的公历日期进行比较这可能吗?6. html5 - iframe src可以引入其他域名或者IP吧iframe src可以是其他域名过IP吧7. mysql - sql数据还原8. javascript - 请问div是个链接,鼠标移上去能出现一个div,比如查看更多按钮,怎么做?9. JS怎么给每相隔一行的TD添加filter滤镜?10. css - flex换行后如何设置行距?(direction:row+warp:warp)

网公网安备