[英]How could I build a tree array from this flat array in Javascript by their's parentId and Id.
我有一个像这样的平面数组,我应该为此建立一个平面数组。 如果pid不为null,则该对象将为其父对象的children属性。 我应该怎么做?
var a = [
{id: 1, pid: null},
{id: 2, pid: 1},
{id: 3, pid: 1},
{id: 4, pid: 3},
{id: 5, pid: 3}
];
预期输出:
var result = [{id: 1, children: [
{id: 2, children: []},
{id: 3, children: [{id: 4}, {id: 5}]}
]}]
您可以使用reduce()
方法并创建递归函数。
var a = [{id: 1, pid: null}, {id: 2, pid: 1}, {id: 3, pid: 1}, {id: 4, pid: 3}, {id: 5, pid: 3}]; function tree(data, parent) { return data.reduce((r, {id,pid}) => { if (parent == pid) { const obj = {id} const children = tree(data, id); if (children.length) obj.children = children; r.push(obj) } return r; }, []) } const result = tree(a, null); console.log(result);
您可以使用单循环方法,该方法也适用于未排序的数组。
var a = [{ id: 1, pid: null }, { id: 2, pid: 1 }, { id: 3, pid: 1 }, { id: 4, pid: 3 }, { id: 5, pid: 3 }], tree = function (data, root) { return data.reduce(function (o, { id, pid }) { o[id] = o[id] || { id }; o[pid] = o[pid] || { id: pid }; o[pid].children = o[pid].children || []; o[pid].children.push(o[id]); return o; }, {})[root].children; }(a, null); console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
在这里使用reduce的两个答案都很棒,一个小问题是,它们都存在多次遍历,即IOW:如果树很大,将会有很多线性搜索。
一种解决方法是先构建地图,然后将地图展平.. mmm,实际上,展平在这里可能是错误的词,也许会扩展.. :)但是您知道了。
下面是一个例子。
const a = [ {id: 1, pid: null}, {id: 2, pid: 1}, {id: 3, pid: 1}, {id: 4, pid: 3}, {id: 5, pid: 3} ]; function flatern(map, parent) { const g = map.get(parent); const ret = []; if (g) { for (const id of g) { const k = {id}; ret.push(k); const sub = flatern(map, id); if (sub) k.children = sub; } return ret; } return null; } function tree(a) { const m = new Map(); a.forEach((i) => { const g = m.get(i.pid); if (!g) { m.set(i.pid, [i.id]); } else { g.push(i.id); } }); return flatern(m, null); } console.log(tree(a));
.as-console-wrapper { max-height: 100% !important; top: 0; }
var a = [
{id: 1, pid: null},
{id: 2, pid: 1},
{id: 3, pid: 1},
{id: 4, pid: 3},
{id: 5, pid: 3}
];
function processToTree(data) {
const map = {};
data.forEach(item => {
map[item.id] = item;
item.children = [];
});
const roots = [];
data.forEach(item => {
const parent = map[item.pid];
if (parent) {
parent.children.push(item);
}
else {
roots.push(item);
}
});
return roots;
}
今天学会了这种方法,我认为这是最好的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.