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)
}
为之则易,不为则难。