美文网首页
api返回数据转成Tree结构(扁平化转树结构)

api返回数据转成Tree结构(扁平化转树结构)

作者: 紫灬楓 | 来源:发表于2022-07-28 18:06 被阅读0次

格式转成antd 的Tree控件所需数据类型

返回数据:
const initTree = [
    {
      id: 1,
      name: "Teacher",
      parent_id: 0,
      full_path: "Teacher",
      description: "1",
      admin_id: "1",
    },
    {
      id: 2,
      name: "Basic",
      parent_id: 1,
      full_path: "Teacehr/Basic",
      description: "1",
      admin_id: "1",
    },
  ];

转换Func:
const toTree = (data) => {
  if (!data) {
    return;
  }
  let nodes = {};
  let parentNodes = {};
  data.forEach((node) => {
    node['key'] = node.full_path
    node['title'] = node.name
    let id = node.id;
    let parent_id = node.parent_id || 'root';
    nodes[id] = node;
    if (parent_id) {
      parentNodes[parent_id] = parentNodes[parent_id] || [];
      parentNodes[parent_id].push(node);
    }
  });
  for (let id in nodes) {
    let node = nodes[id];
    if (parentNodes[id]) {
      node['children'] = parentNodes[id];
    } else {
      node['leaf'] = true;
    }
  }
  return parentNodes['root'];
}

结果:

image.png

相关文章

网友评论

      本文标题:api返回数据转成Tree结构(扁平化转树结构)

      本文链接:https://www.haomeiwen.com/subject/uimxwrtx.html