* 根据实现js版本的
/** * 根节点 parentid=0, 每个节点都有id, parentid字段 * @param items * @returns {*} */function getTree(items) { "use strict"; var children = new Map(); items.forEach(function(item){ if (children.has(item.parentid)) { children.get(item.parentid).push(item); } else { children.set(item.parentid, [item]); } }); items.forEach(function(item) { if (children.has(item.id)) { item.children = children.get(item.id); } }); return children.get(0);}
* test
var items = [{ "id": 4, "parentid": 2, "name": "Laravel"}, { "id": 1, "parentid": 0, "name": "PHP"}, { "id": 43, "parentid": 42, "name": "PHPStorm"}, { "id": 44, "parentid": 42, "name": "EclipsePDT"}, { "id": 2, "parentid": 1, "name": "PHP_Framework"}, { "id": 3, "parentid": 2, "name": "ThinkPHP5"}, { "id": 42, "parentid": 1, "name": "DevTools"}];var c = getTree(items);// console.log(c);console.log(JSON.stringify(c));
output:
[{"id":1,"parentid":0,"name":"PHP","children":[{"id":2,"parentid":1,"name":"PHP_Framework","children":[{"id":4,"parentid":2,"name":"Laravel"},{"id":3,"parentid":2,"name":"ThinkPHP5"}]},{"id":42,"parentid":1,"name":"DevTools","children":[{"id":43,"parentid":42,"name":"PHPStorm"},{"id":44,"parentid":42,"name":"EclipsePDT"}]}]}]
* 在线格式化输出
http://www.bejson.com/