当前位置:网站首页>JS flattened array of number shape structure

JS flattened array of number shape structure

2022-07-04 05:42:00 _ Virgo programmer's daily life

 mounted() {
    
      // It is known that JSON Data in tree structure data
      let jsonData = [
        {
     id: 1, title: ' title 1', parent_id: 0, },
        {
    
          id: 2, title: ' title 2', parent_id: 0,
          children: [
            {
    
              id: 3, title: ' title 2-1', parent_id: 2,
              children: [
                {
    
                  id: 4, title: ' title 3-1', parent_id: 3,
                  children: [
                    {
     id: 5, title: ' title 4-1', parent_id: 4 }
                  ]
                }
              ]
            },
            {
     id: 6, title: ' title 2-2', parent_id: 2 }
          ]
        }
      ];

      console.table(this.flat(jsonData));
}
//mounted in : 
    flat(data) {
    
      return data.reduce((pre, cur) => {
    
        // console.log(cur);
        // The of the object is shown here children Properties and values are deconstructed in an empty array , Deconstruct other attributes and values of the object in i Inside .
        const {
     children = [], ...i } = cur;   //  Be careful  ...i  Can only be written at the end of the deconstruction assignment , Otherwise, the report will be wrong 
        // console.log(i);
        // // console.log(children);
        return pre.concat([{
     ...i }], this.flat(children))  // Using recursive callback , Array merge , Notice here  {...i} It's deconstruction 
      }, []);
    },
  }

The results are as follows :
 Insert picture description here

原网站

版权声明
本文为[_ Virgo programmer's daily life]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207040529279746.html