美文网首页
数组对象扁平化

数组对象扁平化

作者: 北上广_d8bd | 来源:发表于2021-03-24 15:03 被阅读0次
    const arr = [
          {
            id: 1,
            title: "课程 1",
            children: [
              { id: 4, title: "课程 1-1" },
              {
                id: 5,
                title: "课程 1-2",
                children: [
                  { id: 6, title: "课程 1-2-1" },
                  { id: 7, title: "课程 1-2-2" },
                ],
              },
            ],
          },
          { id: 2, title: "课程 2" },
          { id: 3, title: "课程 3" },
        ];
    
    
        function flaten(arr) {
          return arr.reduce((p, v, i) => {
            for (let i = 0; i < p.length; i++) {
              if (p[i].children) {
                delete p[i].children
              }
            }
            return p.concat(v.children ? flaten(v.children).concat(v) : v);
          }, [])
        }
        console.log(flaten(arr))
    
    
     // reduce 功能很强大呦;
    

    相关文章

      网友评论

          本文标题:数组对象扁平化

          本文链接:https://www.haomeiwen.com/subject/dpkhhltx.html