[英]Tree from an associative array
有一个数组:
let docs = [
{ "_id":"1", parent:"_", "title":"one"},
{ "_id":"2", parent:"1", "title":"two"},
{ "_id":"4", parent:"_", "title":"title"},
{ "_id":"5", parent:"4", "title":"www"},
{"_id":"_", "name":"root" },
];
我需要摆脱的是一棵树:
{'_id':'_','name':'root','child':
[
{'_id':'1','parent':'_','title':'one','child':
[
{'_id':'2','parent':'1','title':'two','child':[]}
]
},
{'_id':'4','parent':'_','title':'title','child':
[
{'_id':'6','parent':'4','title':'vvv','child':[]}
]
}
]
}
但是,仅当父元素在列表上始终高于子元素时,我的代码才有效,并且我想使该元素通用。
这是代码:
let node = {};
for (let doc of docs) {
doc.child = [];
node[doc._id] = doc;
if (typeof doc.parent === "undefined")
tree = doc;
else
node[doc.parent].child.push(doc);
}
console.log('tree->', JSON.stringify(tree));
Codepen上的代码: http ://codepen.io/alex183/pen/OWvrPG?editors=0112
您可以使用reduce
创建递归函数
let docs = [ { "_id":"1", parent:"_", "title":"one"}, { "_id":"2", parent:"1", "title":"two"}, { "_id":"4", parent:"_", "title":"title"}, { "_id":"5", parent:"4", "title":"www"}, {"_id":"_", "name":"root" } ]; function makeTree(data, parent = undefined) { return data.reduce(function(r, e) { if (e.parent == parent)(e.child = makeTree(data, e._id), r.push(e)) return r; }, []) } console.log(makeTree(docs))
这是Array#reduce
和Map
的建议。 它预先对数组进行排序。
var docs = [{ _id: "1", parent: "_", title: "one" }, { _id: "2", parent: "1", title: "two" }, { _id: "4", parent: "_", title: "title" }, { _id: "5", parent: "4", title: "www" }, { _id: "_", name: "root" }], order = { undefined: -2, _: -1 }, tree = docs .sort((a, b) => (order[a.parent] || a.parent) - (order[b.parent] || b.parent) || a._id - b._id) .reduce( (m, a) => ( m .get(a.parent) .push(Object.assign({}, a, { child: m.set(a._id, []).get(a._id) })), m ), new Map([[undefined, []]]) ) .get(undefined); console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
快速而肮脏的方法是使用排序功能。
docs = docs.sort((a, b) => (a._id - b._id));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.