在用一些树表插件的时候,这些树表插件都会要求数据的机构是带children属性的对象数组,而后台如果没有转换为这种形式的list,就需要在前端进行转换。

  function listToTreeList(list) { // 将普通列表转换为树结构的列表
    if (!list || !list.length) {
      return []
    }
    let treeListMap = {};
    for (let item of list) {
      treeListMap[item.id] = item
    }
    for (let i = 0; i < list.length; i++) {
      if (list[i].parentId && treeListMap[list[i].parentId]) {
        if (!treeListMap[list[i].parentId].children) {
          treeListMap[list[i].parentId].children = []
        }
        treeListMap[list[i].parentId].children.push(list[i]);
        list.splice(i, 1);
        i--
      }
    }
    return list
  }

封装成一个函数,方便多次调用。

 

"对不起,我没能变成你喜欢的样子。"

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-27
  • 2022-12-23
  • 2022-12-23
  • 2022-01-16
  • 2021-09-27
猜你喜欢
  • 2021-08-17
  • 2021-07-22
  • 2022-12-23
  • 2022-02-16
  • 2021-04-23
  • 2022-03-11
  • 2022-12-23
相关资源
相似解决方案