如何实现最多N个级别的递归在Node js的每个级别上都有对象数组?

时间:2019-03-18 06:32:46

标签: javascript node.js recursion

我想实现此链接中给出的json的递归 Check JSON Here我的递归解决方案仅适用于一个级别,因此请向我建议这样的解决方案,以便我可以达到N个级别。

我已经在下面编写了一个递归函数,但是它只能工作到一个级别。

Report.GetSections = function(Section1) {
  let TempSectionItem = [];
  let TempAllSection = [];

  let sortOrder = 0;
  let id = Section1.id;
  let parentId = Section1.parentId;
  let title = Section1.label;
  sortOrder = Section1.SortOrder;
  let SectionType = Section1.sectionType;

  if (Section1.sections.length === 0) {
    let TempSectionItem = [];
    let allsection = [];
    let tempsection1 = [];
    let tempsection = new Section(id, title, parentId, SectionType, sortOrder, TempSectionItem, allsection);
    tempsection1.push(tempsection);
    return tempsection1;
  }
  for (let i = 0; i < Section1.sections.length; i++) {

    var tempsection = new Section(id, title, parentId, SectionType, sortOrder, TempSectionItem, Report.GetSections(Section1.sections[i]));
    TempAllSection.push(tempsection);

  }

  return TempAllSection;
}

1 个答案:

答案 0 :(得分:0)

这是上述问题的递归解决方案。

  class Section {
  constructor(id, title, parentId, sectionType, sortOrder, sectionItem, section) {
    this.id = id;
    this.title = title;
    this.parentId = parentId;
    this.sectionType = sectionType;
    this.section = section;
    this.sortOrder = sortOrder;
    this.SectionItems = sectionItem;

  }
}

这是递归函数:

  Report.GetSections = function (Section1) {
    let TempSectionItem = [];let sortOrder = 0;
    let id = Section1.id;
    let parentId = Section1.parentId;
    let title = Section1.label;
    sortOrder = Section1.sortOrder;
    let SectionType = Section1.sectionType;
if (Section1.sections.length === 0) {
      let allsection = [];
      let tempsection = new Section(id, title, parentId, SectionType, sortOrder, TempSectionItem, allsection);
      return tempsection;
    }

    let TempLevelSections=[];
    for (let i = 0; i < Section1.sections.length; i++) {
      TempLevelSections.push(Report.GetSections(Section1.sections[i]));
    }
    var section=new Section(id, title, parentId, SectionType, sortOrder, TempSectionItem, TempLevelSections);
    return section;
  }