huyueshan

导航

扁平数据根据`parentId`生成树结构

根据每项的parentId,生成具体树形结构的对象。

const nest = (items, id = null, link = 'parent_id') =>
  items
    .filter(item => item[link] == id)
    .map(item => ({ ...item, children: nest(items, item.id) }));


const comments = [
  { id: 1, parent_id: null },
  { id: 2, parent_id: 1 },
  { id: 3, parent_id: 1 },
  { id: 4, parent_id: 2 },
  { id: 5, parent_id: 4 }
];

const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]



// 根据数据属性层级关系生成数据树
    tree(items, sums) {
        const sumob = {};
        sums.forEach(it => {
            sumob[it.id] = it.totalCount
        });
        const n = ['enterprise', 'area', 'company', 'project', 'region', 'person'];
        const ob = {}
        items.forEach(item => {
            n.forEach((it, i) => {
                ob[item[it + 'Id']] = {
                    name: item[it + 'Name'],
                    id: item[it + 'Id'],
                    parentId: i ? item[n[i - 1] + 'Id'] : null,
                    off: true,
                    v1: 1,
                    v2: sumob[item[it + 'Id']] || 0,
                }
            })
        });
        const fn = (data) => {
            data.forEach(item => {
                if (item.children.length) {
                    fn(item.children);
                    item.v1 = item.children.reduce((tol, it) => tol + it.v1, 0)
                }
            })
            return data
        }
        return fn(this.nest(Object.values(ob)));
    },
 

 

posted on 2019-12-12 23:05  huyueshan  阅读(2409)  评论(1编辑  收藏  举报