Skip to content

treeToFlat

树形数据结构扁平化

参数

参数名参数类型参数说明
target`Record<string, unknown>Record<string, unknown>[]`
subsetKeystring树形子集的键名(默认是children)

返回值

{ Record<string, unknown>[] }

源代码&使用

ts
import { treeToFlat } from '@manzhixing/utilsxy';

const provinceList = [
  {
    id: "1000",
    label: "湖北省",
    children: [
      {
        id: "1001",
        pid: "1000",
        label: "武汉",
        children: [
          { id: "100101", pid: "1001", label: "洪山区" },
          { id: "100102", pid: "1001", label: "武昌区" },
          { id: "100103", pid: "1001", label: "汉阳区" },
        ],
      },
      { id: "1020", pid: "1000", label: "咸宁" },
      { id: "1022", pid: "1000", label: "孝感" },
      { id: "1034", pid: "1000", label: "襄阳" },
      { id: "1003", pid: "1000", label: "宜昌" },
    ],
  },
  {
    id: "1200",
    value: "江苏省",
    label: "江苏省",
    children: [
      { id: "1201", pid: "1200", label: "南京" },
      { id: "1202", pid: "1200", label: "苏州" },
      { id: "1204", pid: "1200", label: "扬州" },
    ],
  },
];

const provinceFlat = treeToFlat(provinceList);

// 返回值
[
  {
    id: '1000',
    label: '湖北省',
  },
  {
    id: '1200',
    value: '江苏省',
    label: '江苏省',
  },
  {
    id: '1001',
    pid: '1000',
    label: '武汉',
  },
  {
    id: '1020',
    pid: '1000',
    label: '咸宁',
  },
  {
    id: '1022',
    pid: '1000',
    label: '孝感',
  },
  {
    id: '1034',
    pid: '1000',
    label: '襄阳',
  },
  {
    id: '1003',
    pid: '1000',
    label: '宜昌',
  },
  {
    id: '1201',
    pid: '1200',
    label: '南京',
  },
  {
    id: '1202',
    pid: '1200',
    label: '苏州',
  },
  {
    id: '1204',
    pid: '1200',
    label: '扬州',
  },
  {
    id: '100101',
    pid: '1001',
    label: '洪山区',
  },
  {
    id: '100102',
    pid: '1001',
    label: '武昌区',
  },
  {
    id: '100103',
    pid: '1001',
    label: '汉阳区',
  },
];
ts
/*
 * @Author: Chengbotao
 * @Contact: https://github.com/chengbotao
 */

export function treeToFlat(
  target: Record<string, unknown> | Record<string, unknown>[],
  subsetKey = 'children'
) {
  const copyTree = Array.isArray(target) ? Array.prototype.slice.call(target) : [target];
  const flat = [];
  while (copyTree.length) {
    const node = copyTree.shift();
    const { [subsetKey]: children, ...rest } = node;
    flat.push(rest);
    if (children) {
      Array.prototype.push.apply(copyTree, node.children);
      // Array.prototype.unshift.apply(copyTree, node.children);
    }
  }
  return flat;
}