前臺接收到的數據格式spa
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; }
調用方法code
var treeData=listToTree(rows);
技術交流QQ羣:15129679blog