javascript 无限分类
Posted mingzhanghui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 无限分类相关的知识,希望对你有一定的参考价值。
* 根据php无限分类实现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"}]}]}]
* 在线json校验格式化输出
http://www.bejson.com/
以上是关于javascript 无限分类的主要内容,如果未能解决你的问题,请参考以下文章