递归遍历删除children为[]的children

      const arr = [
        {
          value: 'zhejiang',
          label: 'Zhejiang',
          children: [
            {
              value: 'hangzhou',
              label: 'Hangzhou',
              children: [
                {
                  value: 'xihu',
                  label: 'West Lake',
                },
              ],
            },
          ],
        },
        {
          value: 'jiangsu',
          label: 'Jiangsu',
          children: [
            {
              value: 'nanjing',
              label: 'Nanjing',
              children: [],
            },
          ],
        },
        {
          value: 'anhui',
          label: 'anhui',
          children: [],
        },
      ];

      const recursionRemoveEmpty = (data) => {
        data = data.filter((item) => {
          if (item.children) item.children = recursionRemoveEmpty(item.children);
          if (item.children && item.children.length === 0) delete item.children;
          return item;
        });
        return data;
      };

      const newArr = recursionRemoveEmpty(JSON.parse(JSON.stringify(arr)));

      console.log(arr);
      console.log(newArr);

原文地址:https://www.cnblogs.com/wuqilang/p/14959348.html