javascript - js writes a recursion to restructure the data structure into another structure
天蓬老师
天蓬老师 2017-06-28 09:27:56
0
3
898

Now we have the following data structure:

[{ 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: "单片机开发" }]

Write a JS method to convert it into the following format data:

[{ 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: "单片机开发" }] }]
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all (3)
Ty80
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);
    学习ing
    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));

      某草草

      Please refer to it

      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 }, [])
        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!