js数组扁平数据结构转tree

记录一下日常学习,js数组扁平数据结构转tree

演示数据

const arr = [
  { id: 1, name: '部门1', pid: 0 },
  { id: 2, name: '部门2', pid: 1 },
  { id: 3, name: '部门3', pid: 1 },
  { id: 4, name: '部门4', pid: 3 },
  { id: 5, name: '部门5', pid: 4 },
]

1.map存储 唯一性

function formatDataTree (arr, key, parentKey) {
  const result = [];
  const itemMap = {};
  for (const item of arr) {
    const id = item[key];
    const pid = item[parentKey];

    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      }
    }

    itemMap[id] = {
      ...item,
      children: itemMap[id]['children']
    }

    const treeItem = itemMap[id];

    if (pid === 0) {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        }
      }
      itemMap[pid].children.push(treeItem)
    }

  }
  return result;
}

2.递归

function translateDataToTreeAllTreeMsg (data, parentKey, parentIDKey) {
  let parent = data.filter((value) => Number(value[parentKey]) <= 0);// 父数据
  let children = data.filter((value) => Number(value[parentKey]) > 0);// 子数据
  let translator = (parent, children) => {
    parent.forEach((parent) => {
      parent.children = [];
      children.forEach((current, index) => {
        if (current[parentKey] === parent[parentIDKey]) {
          const temp = JSON.parse(JSON.stringify(children));
          temp.splice(index, 1);
          translator([current], temp);
          typeof parent.children !== "undefined"
            ? parent.children.push(current)
            : (parent.children = [current]);
        }
      });
    });
  };
  translator(parent, children);
  return parent;
}

输出

微信截图_20220808153617.png

你可能感兴趣的:(js数组扁平数据结构转tree)