Skip to content

函数: mapTreeList()

ts
function mapTreeList<T, R>(
   data, 
   callback, 
   children?): R[];

定义于: tree.ts:390

映射树的每个节点,返回一棵结构相同、内容重塑的新树形数组。

类型参数

类型参数默认类型
Tany
Rany

参数

参数类型描述
dataT[]树形数组
callback(node, level) => R每个节点触发的映射函数,签名 (node, level)level 为层级(根为 0),返回映射后的新节点对象;子级会按同样规则递归映射并挂回新节点的 children 字段
childrenkeyof T子级集合的键名,默认 'children'

返回值

R[]

备注

不改变原数据(回调只需返回新对象,子级由本函数负责递归拼装);若只想原地遍历而不重建结构,请用 eachTreeList

示例

ts
const list = [
  {
    name: 'option1', id: 1,
    children: [
      { name: 'option1.1', id: 3 },
    ],
  },
  { name: 'option2', id: 2 },
]

mapTreeList(list, n => ({ value: n.id, label: n.name }))
// => [
//   { value: 1, label: 'option1', children: [{ value: 3, label: 'option1.1' }] },
//   { value: 2, label: 'option2' },
// ]