----- cornerstone of JS array is converted into a tree structure function

We often do background management system when the data needs to be assembled into a tree structure package, specifically where this method of encapsulation:

let data = [
    { id: 1, text: 't11', parentId: 0 },
    { id: 2, text: 't11', parentId: 0 },
    { id: 3, text: 't11', parentId: 1 },
    { id: 4, text: 't11', parentId: 1 },
    { id: 5, text: 't11', parentId: 3 },
    { id: 6, text: 't11', parentId: 2 }
]
function treeData (data, id, parentId, childName) {
    let cloneData = JSON.parse(JSON.stringify(data))
    return cloneData.filter((father) => {
        let newArr = cloneData.filter((child) => {
            return father[id] === child[parentId]
        })
        father[childName] = newArr
        return father[parentId] === 0
    })
}
let msg = treeData(data, 'id', 'parentId', 'childaaa')
console.log(msg)

 

Guess you like

Origin www.cnblogs.com/style-hyh/p/12059809.html