JavaScript 给树形(层级)数组添加层级标识

const arrayTreeSetLevel = (array, levelName = 'level', childrenName = 'children') => {
    if (!Array.isArray(array)) return []
    const recursive = (array, level = 0) => {
        level++
        return array.map(v => {
            v[levelName] = level
            const child = v[childrenName]
            if (child && child.length) recursive(child, level)
            return v
        })
    }
    return recursive(array)
}
posted @ 2021-01-25 15:52  demo_you  阅读(352)  评论(0编辑  收藏  举报