• 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/

  • 相关阅读:
    Python基础学习笔记(10)形参 命名空间
    10 练习题:形参 命名空间
    09 练习题:函数、参数
    4.题库
    第三章:构造NFA DFA
    第二章
    第一章
    83.jquery的筛选与过滤
    82.认识jQuery以及选择器
    81.案例 初始化、拖拽、缓冲
  • 原文地址:https://www.cnblogs.com/mingzhanghui/p/9419856.html
Copyright © 2020-2023  润新知