【问题标题】:How to Implement recursion upto N levels Having array of objects at each level in Node js?如何实现最多 N 个级别的递归在 Node js 中的每个级别都有对象数组?
【发布时间】:2019-03-19 13:42:05
【问题描述】:

我想为此链接中给出的 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;
}

【问题讨论】:

    标签: javascript node.js recursion


    【解决方案1】:

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

      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;
      }
    

    【讨论】:

      猜你喜欢
      • 2011-05-28
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多