数组扁平化与树形结构的相互转化

一、树形结构转换

let arr = [
  { id: 1, title: "标题1", parent_id: 0 },
  { id: 2, title: "标题2", parent_id: 0 },
  { id: 3, title: "标题2-1", parent_id: 2 },
  { id: 4, title: "标题3-1", parent_id: 3 },
  { id: 5, title: "标题2-2", parent_id: 2 },
];
//数组扁平化处理,先转化为key-value结构
function convert(arr) {
  let map = arr.reduce((prev, curv) => {
    prev[curv.id] = curv;
    return prev;
  }, {});
  let result = [];
  for (const item of arr) {
    if (item.parent_id === 0) {
      result.push(item);
    }
    if (item.parent_id in map) {
      //如果存在于父元素则提取出来,并给父元素添加children属性
      const parent = map[item.parent_id];
      parent.children = parent.children || [];
      parent.children.push(item);
    }
  }
  return result;
}

二、数组扁平化处理

// 将树结构扁平化处理
let arr = [
  { id: 1, title: "标题1", parent_id: 0 },
  {
    id: 2,
    title: "标题2",
    parent_id: 0,
    children: [
      {
        id: 3,
        title: "标题2-1",
        parent_id: 2,
        children: [{ id: 4, title: "标题3-1", parent_id: 3 }],
      },
      { id: 5, title: "标题2-2", parent_id: 2 },
    ],
  },
];
function flatten(arr) {
  return arr.reduce((prev, curv) => {
    const { id, title, parent_id, children = [] } = curv;
    return prev.concat([{ id, title, parent_id }], flatten(children));
  }, []);
}

你可能感兴趣的:(JavaScript,javascript,前端)