js实现扁平数据转化成树结构数据

1. 递归遍历

function transformTree (list) {
    
    
    const tree = []
    
    for (let i = 0, len = list.length; i < len; i++) {
    
    
        if (!list[i].pid) {
    
    
            const item = queryChildren(list[i], list)
            
            tree.push(item)
        }
    }
    
    return tree
}

function queryChildren (parent, list) {
    
    
    const children = []
    
    for (let i = 0, len = list.length; i < len; i++) {
    
    
        if (list[i].pid === parent.id) {
    
    
            const item = queryChildren(list[i], list)

            children.push(item)
        }
    }
    
    if (children.length) {
    
    
        parent.children = children
    }
    
    return parent
}

2. 使用map遍历一次

function transformTree (list, options = {
     
     }) {
    
    
    const {
    
    
        keyField = 'id',
        childField = 'children',
        parentField = 'parent'
    } = options

    const tree = []
    const record = {
    
    }

    for (let i = 0, len = list.length; i < len; i++) {
    
    
        const item = list[i]
        const id = item[keyField]

        if (!id) {
    
    
            continue
        }

        if (record[id]) {
    
    
            item[childField] = record[id]
        } else {
    
    
            item[childField] = record[id] = []
        }

        if (item[parentField]) {
    
    
            const parentId = item[parentField]

            if (!record[parentId]) {
    
    
                record[parentId] = []
            }

            record[parentId].push(item)
        } else {
    
    
            tree.push(item)
        }
    }

    return tree
}

猜你喜欢

转载自blog.csdn.net/weixin_46996561/article/details/132620194