All files / formatTreeSelectProps formatTreeSelectProps.ts

100% Statements 6/6
100% Branches 5/5
100% Functions 2/2
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112                                                                                                                                                                1x               3x 4x       2x                       2x            
/**
 * @description 格式化tree属性为TreeSelect所需
 * @function formatTreeSelectProps
 * @param {object} obj - 入参对象
 * @param {object} obj.tree - 原始tree
 * @param {object} [obj.fieldNames={id: 'key', label: 'label', children: 'children'}] - 格式化tree所需的属性
 * @param {boolean} [obj.parentSelectable = false] - 父级是否可选择,默认不可选
 * @returns {array} 格式化后符合TreeSelect的tree
 * @author liukun <919590347@qq.com>
 * @example
import { formatTreeSelectProps } from '@wont/utils'
 
const beforeTree = [
  {
    id: 1,
    label: '1-1',
    children: [
      {
        id: 11,
        label: '1-1-1',
        children: [
          {
            id: 111,
            label: '1-1-1-1',
          },
        ],
      },
    ],
  },
  {
    id: 2,
    label: '2-1',
  },
]
const afterTree = [
  {
    id: 1,
    value: 1,
    label: '1-1',
    selectable: false,
    children: [
      {
        id: 11,
        value: 11,
        label: '1-1-1',
        selectable: false,
        children: [
          {
            id: 111,
            value: 111,
            label: '1-1-1-1',
          },
        ],
      },
    ],
  },
  {
    id: 2,
    value: 2,
    label: '2-1',
  },
]
formatTreeSelectProps({
  tree: beforeTree,
})
// return afterTree
 */
interface FieldNames {
  value: string
  label: string
  children: string
}
interface Params {
  tree: Record<string, any>[]
  fieldNames?: FieldNames
  parentSelectable?: boolean
}
 
type FormatTreeSelectProps = (params: Params) => Params['tree']
 
export const formatTreeSelectProps: FormatTreeSelectProps = ({
  tree,
  fieldNames = {
    value: 'id',
    label: 'label',
    children: 'children',
  },
  parentSelectable = false,
}) => tree.map((item) => {
  if (
    Array.isArray(item[fieldNames.children])
      && item[fieldNames.children].length > 0
  ) {
    return {
      ...item,
      selectable: parentSelectable,
      value: item[fieldNames.value],
      label: item[fieldNames.label],
      children: formatTreeSelectProps({
        tree: item[fieldNames.children],
        fieldNames,
        parentSelectable,
      }),
    }
  }
  return {
    ...item,
    value: item[fieldNames.value],
    label: item[fieldNames.label],
  }
})