1

How can I write this code in underscore.js?

for(var i=0; i<scope.courseContent.sections.length; i++){
        if(scope.courseContent.sections[i].pages.length){
            ctrl.pages.push({'content': scope.courseContent.sections[i].content});
            for(var j=0; j<scope.courseContent.sections[i].pages.length; j++){
                ctrl.pages.push({'content':scope.courseContent.sections[i].pages[j].content});
            }
        }
        else{
            if(scope.courseContent.sections[i].title == 'Course Title' || scope.courseContent.sections[i].title == 'Introduction'){
                ctrl.pages.push({'content':scope.courseContent.sections[i].content});
            }
        }
}

I tried this using nested .each loop but this isnt woking. Heres my approach:

_.each(scope.courseContent.sections, function(sections){
        if(sections.pages.length){
            ctrl.pages.push({'content': scope.courseContent.sections.content});
            _.each(sections.pages, function(page){
                ctrl.pages.push({'content':scope.courseContent.sections.pages.content});    
            });
        }
        else{
            if(scope.courseContent.sections.title == 'Course Title' || scope.courseContent.sections.title == 'Introduction'){
                ctrl.pages.push({'content':scope.courseContent.sections.content});
            }
        }
});

1 Answer 1

1

The problem is that sections, pages etc are arrays, in the original code since we're using for loop, items are accessed using iteration index like scope.courseContent.sections[i].content, but with your underscore attempt, you're trying to access properties of each item directly from the arrays using . which won't work as expected.

When you use underscore, you get each item as the first argument to call back, So I think your code should be:

_.each(scope.courseContent.sections, function(section) {
  if (section.pages.length) {
    ctrl.pages.push({
      'content': section.content
    });
    _.each(section.pages, function(page) {
      ctrl.pages.push({
        'content': page.content
      });
    });
  } else if (section.title == 'Course Title' || section.title == 'Introduction') {
      ctrl.pages.push({
        'content': section.content
      });
    }
});

or you can add a second parameter in your callback signature, which will be the index of current item, like:

_.each(scope.courseContent.sections, function(section,i) {

and acceess items with index just like original code: scope.courseContent.sections[i].content, but that's unnecessary.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.