对象数组嵌套多层childList,如何每层每个childList都遍历改变值

如果你有一个嵌套多层的对象数组,其中包含childList属性,并且想要遍历每一层的每个childList并将其id加1,可以使用递归的方法来实现。以下是一个示例代码,演示如何遍历并修改每层的childList中的id:   

getGroupListTrees(data:any):any {

      if (Array.isArray(data)) {

        return data.map(item => this.getGroupListTrees(item));

      } else if (typeof data === 'object' && data !== null) {

        const result:IObject = {};

        for (let key in data) {

          if (key === 'faqCategoryName') {

            result.label = data[key];

          } else if (key === 'id') {

            result.value = data[key];

          } else if (key === 'childList') {

            result.children = this.getGroupListTrees(data[key]);

          } else {

            result[key] = this.getGroupListTrees(data[key]);

          }

        }

        return result;

      } else {

        return data;

      }

    },


const arr = getGroupListTrees(res.data.list);

你可能感兴趣的:(javascript,开发语言,ecmascript)