Skip to content

treeMap

创建新的树结构

示例

js
const output = mapTree(
  input,
  (node, index, parent, depth) => ({
    ...node,
    context: { ...node, index, depth }
  }),
  { childrenKey: 'children' }
)
js
// input
[
  {
    id: '1',
    parentId: '0',
    children: [
      {
        id: '1-1',
        parentId: '1',
        children: [{ id: '1-1-1', parentId: '1-1' }]
      }
    ]
  }
];

// output:
[
  {
    id: '1',
    parentId: '0',
    context: {
      id: '1',
      parentId: '0',
      index: 0,
      depth: 0
    },
    children: [
      {
        id: '1-1',
        parentId: '1',
        context: {
          id: '1-1',
          parentId: '1',
          index: 0,
          depth: 1
        },
        children: [
          {
            id: '1-1-1',
            parentId: '1-1',
            context: {
              id: '1-1-1',
              parentId: '1-1',
              index: 0,
              depth: 2
            }
          }
        ]
      }
    ]
  }
]

参数

名称说明类型可选值默认值
tree树数据Array--
fn返回新结构的函数(node, index, parent, depth) => any--
options参数配置TreeMapOptions--

TreeMapOptions

名称说明类型可选值默认值
childrenKey子节点的名string-"children"
parent父节点object|null-null
depth起始的深度number-0

返回值

(Array): 返回新的树结构