Skip to content

key值拼接树

一维数组通过父子节点间的key值可以将其拼接为多维的树型数组

案例代码如下,其中cparentid为父级的拼接标识属性,cguid为自身的拼接标识属性,children则是父级中子集存放的属性

js
utilToTree(arr, rootItem = '') {
            function toTree({
                value = arr, // 需要处理的数组
                fatherKey = 'cparentid', // 父级的key值
                selfKey = 'cguid', // 自身的key值
                childrenKey = 'children', // 向父级的该key值上拼接
                rootValue = rootItem // 根节点的父级key值标识
            } = {}) {
                // 复制对象
                value = JSON.parse(JSON.stringify(value))
                for (let i = 0; i < value.length; i++) {
                    const itemI = value[i]
                    if (itemI[fatherKey] === rootValue) {
                        continue
                    }
                    // 除了根节点的n对象进行n次拼接,然后根据根节点标识剔除非根节点的数据就得到了树形结构
                    for (let j = 0; j < value.length; j++) {
                        if (i === j) {
                            continue
                        }
                        const itemJ = value[j]
                        if (itemI[fatherKey] === itemJ[selfKey]) {
                            if (!itemJ[childrenKey] || Object.prototype.toString.call(itemJ[childrenKey]) !== '[object Array]') {
                                itemJ[childrenKey] = []
                            }
                            itemJ[childrenKey].push(itemI)
                            break
                        }
                    }
                }
                return value.filter(item => item[fatherKey] === rootValue)
            }
            return toTree()
        }

鄂ICP备19018246号-1