码迷,mamicode.com
首页 > 编程语言 > 详细

javascript 无限分类

时间:2018-08-04 21:03:17      阅读:452      评论:0      收藏:0      [点我收藏+]

标签:laravel   无限   thinkphp5   framework   name   for   com   get   targe   

* 根据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 无限分类

标签:laravel   无限   thinkphp5   framework   name   for   com   get   targe   

原文地址:https://www.cnblogs.com/mingzhanghui/p/9419856.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!