前台接收到的数据格式

var rows=[{
    parent: 'root',
    id: 'DC',
    title: '集团'
},
{
    parent: 'DC',
    id: '01',
    title: '上海本部'
},
{
    parent: 'DC',
    id: '02',
    title: '中华企业'
},
{
    parent: '02',
    id: '0200',
    title: '中华企业股份有限公司本部'
},
{
    parent: '02',
    id: '0201',
    title: '上海古北(集团)有限公司'
},
{
    parent: '0201',
    id: '020100',
    title: '上海古北(集团)有限公司本部'
},
{
    parent: '0201',
    id: '020101',
    title: '上海古北顾村置业有限公司'
},
{
    parent: '0201',
    id: '020102',
    title: '上海古北京宸置业发展有限公司'
},
{
    parent: '0201',
    id: '020103',
    title: '苏州洞庭房地产发展有限公司'
}]

 

 

function listToTree(data, options) {

    options = options || {};
    var ID_KEY = options.idKey || 'id';
    var PARENT_KEY = options.parentKey || 'parent';
    var CHILDREN_KEY = options.childrenKey || 'children';

    var tree = [],
    childrenOf = {};
    var item,
    id,
    parentId;

    for (var i = 0, length = data.length; i < length; i++) {
        item = data[i];
        id = item[ID_KEY];
        parentId = item[PARENT_KEY] || 0;
        // every item may have children
        childrenOf[id] = childrenOf[id] || [];
        // init its children
        item[CHILDREN_KEY] = childrenOf[id];
        if (parentId != 0) {
            // init its parent's children object
            childrenOf[parentId] = childrenOf[parentId] || [];
            // push it into its parent's children object
            childrenOf[parentId].push(item);
        } else {
            tree.push(item);
        }
    };

    return tree;
}

 调用方法

var treeData=listToTree(rows);

技术交流QQ群:15129679

相关文章:

  • 2021-08-06
  • 2022-12-23
  • 2022-02-15
  • 2022-02-08
  • 2022-12-23
  • 2021-11-29
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
  • 2021-08-11
  • 2021-07-25
相关资源
相似解决方案