数组扁平化

发布时间 2023-04-08 17:00:57作者: 张铄洋
    var arr = [
      {
        id: 1,
        title: '我是1目录',
        children: [
          {
            id: 11,
            title: '我是1-1目录',
            children: [
              {
                id: 111,
                title: '我是1-1-1目录',
                children: []
              }
            ]
          },
          {
            id: 12,
            title: '我是1-2目录',
            children: []
          }
        ]
      },
      {
        id: 2,
        title: '我是2目录',
        children: [
          {
            id: 21,
            title: '我是2-1目录',
            children: []
          }
        ]
      }
    ]
    flatten(arr) {
      return arr.reduce((result, item) => {
        return result.concat(
          item,
          Array.isArray(item.children1) ? this.flatten(item.children1) : []
        );
      }, []);
    }