基础配置项

  1. const treeOptions = {
  2. key_id: 'id' ,
  3. key_parent: 'parentId' ,
  4. key_child: 'children',
  5. empty_children: false
  6. };

方案一

  1. function treeDataTranslate(data, options = treeOptions) {
  2. var tree = []
  3. var temp = {}
  4. for (var i = 0; i < data.length; i++) {
  5. temp[data[i][options.key_id]] = data[i]
  6. }
  7. for (var k = 0; k < data.length; k++) {
  8. if (temp[data[k][options.key_parent]] &&
  9. data[k][options.key_id] !== data[k][options.key_parent]) {
  10. if (!temp[data[k][options.key_parent]][options.key_child]) {
  11. temp[data[k][options.key_parent]][options.key_child] = []
  12. }
  13. temp[data[k][options.key_parent]][options.key_child].push(data[k])
  14. } else {
  15. tree.push(data[k])
  16. }
  17. }
  18. console.log('tree', tree)
  19. return tree
  20. };

方案二

  1. function treeDataTranslate(data, options = treeOptions){
  2. data.forEach(element => {
  3. let parentId = element[treeOptions.key_parent];
  4. if(!!parentId) {
  5. data.forEach(ele => {
  6. if(ele[treeOptions.key_id] == parentId) {
  7. if(!ele[treeOptions.key_child]) {
  8. ele[treeOptions.key_child] = [];
  9. }
  10. ele[treeOptions.key_child].push(element);
  11. }
  12. });
  13. }
  14. });
  15. let tree = data.filter(ele => !ele[treeOptions.key_parent]);
  16. console.log('tree', tree)
  17. return tree;
  18. };

方案三

  1. function treeDataTranslate(data, options = treeOptions) {
  2. const group = {};
  3. data.forEach((item) => {
  4. const parentId = item[treeOptions.key_parent];
  5. if(!group.hasOwnProperty(parentId)) {
  6. group[parentId] = [];
  7. }
  8. group[parentId].push(item);
  9. });
  10. data.forEach((item) => {
  11. var id = item[treeOptions.key_id];
  12. if(group.hasOwnProperty(id)) {
  13. item[treeOptions.key_child] = group[id];
  14. }
  15. });
  16. console.log('group', group)
  17. return group["null"];
  18. }

方案四

  1. /*
  2. * @list 数组对象
  3. * @tree 树形列表
  4. * @parentId 根节点Id值
  5. */
  6. function treeDataTranslate (list, tree, parentId) {
  7. list.forEach(item => {
  8. // 判断是否为父级菜单
  9. if (item[treeOptions.key_parent] === parentId) {
  10. const child = {
  11. ...item,
  12. key: item.key || item[treeOptions.key_id],
  13. children: []
  14. }
  15. // 迭代 list, 找到当前菜单相符合的所有子菜单
  16. treeDataTranslate(list, child.children, item[treeOptions.key_id])
  17. // 删掉不存在 children 值的属性
  18. if (child.children.length <= 0) {
  19. delete child.children
  20. }
  21. // 加入到树中
  22. tree.push(child)
  23. }
  24. })
  25. }