数据扁平化笔记。

数据结构:

let datas = [
  {
    id: 1,
    checked: true,
    name: '第一阶段',
    children: [
      {
        id: 2,
        checked: false,
        name: '第一章',
        children: [
          {
            id: 3,
            checked: false,
            name: '简介',
          },
          {
            id: 4,
            checked: false,
            name: '能做什么',
          }
        ]
      },
      {
        id: 5,
        checked: false,
        name: '第二章',
        children: [
          {
            id: 6,
            checked: false,
            name: '简介',
          },
          {
            id: 7,
            checked: false,
            name: '能做什么',
          }
        ]
      },
    ]
  },
  {
    id: 8,
    checked: false,
    name: '第二阶段',
    children: [
      {
        id: 9,
        checked: false,
        name: '第一章',
        children: [
          {
            id: 10,
            checked: false,
            name: '简介',
          },
          {
            id: 11,
            checked: false,
            name: '能做什么',
          }
        ]
      }
    ]
  },
  {
    id: 12,
    checked: false,
    name: '第三阶段',
    children: [
      {
        id: 13,
        checked: false,
        name: '第一章',
        children: [
          {
            id: 14,
            checked: true,
            name: '这是进阶章',
          },
          {
            id: 15,
            checked: false,
            name: '能做什么',
          }
        ]
      }
    ]
  },
];
数据扁平化(针对有对象)普通写法:
    function flat (items) {
      let newArr = []; // 存储扁平化数组
      items.forEach(item => {
        newArr.push(item);
        if (Array.isArray(item.children)) {
          newArr = newArr.concat(item.children)
          flat(item.children);
        }
      });

      return newArr;
    }
数据扁平化reduce写法:
    function flat (items, d = 0) {
      return items.reduce((prev, current) => {
        return d > 0 ? prev.concat(Array.isArray(current.children) ? flat(current.children, d + 1) : current) : items.slice();
      }, [])
    }

 

上一篇:屏幕中间弹框的一种写法


下一篇:matlab练习程序(多圆交点)