Home Assign a value to every object in an array without loop
Reply: 0

Assign a value to every object in an array without loop

user2175
1#
user2175 Published in June 19, 2018, 2:31 pm

I'm adding a simple commenting component to angular 1 application. The object I get from the server looks like this:

comments":[
        {"id":1,"content":"this is my first comment","approved":1,"replies":[]},
        {"id":2,"content":"this is the second","approved":1,"replies":[
          {"priority_id":0,"content":"content of a reply","approved":1},
          {"priority_id":0,"content":"content of a second reply","approved":1}]
        }
      ]

At the moment I'm using 2 loops in the controller to assign a "pending" value to each comment and reply having approved:0

It looks like this:

angular.forEach($scope.comments, function (comment) {
          if (comment.approved === 0) {
            comment.pending = true;
        }
          comment.replies = comment.replies || [];

          angular.forEach(comment.replies, function (reply) {
          if (reply.approved === 0) {
            reply.pending = true;
            }
          });
      });

Is there a better, shorter way to obtain that? Javascript is not exactly my forte. Do I really need to loop in the controller? Maybe I can somehow pass the value from ng-repeat? Thanks in advance!

Thanks to Joe I got to know a better way than looping. I have marked his answer as the solution although I had to modify the code a bit to work because my application uses angular 1.4 which is incompatible with arrow functions. Here's the code:

$scope.comments.map(function(comment) {

                  if (comment.approved === 0) {
                    comment.pending = true;
                  }

                  comment.replies = comment.replies || [];

                  comment.replies.map(function(reply){
                     if (reply.approved === 0) {
                    reply.pending = true;
                    }
                    return reply.approved;
                  });
                  return comment.approved;

                });

It does not look as neat as Joe's but it still uses map method which, as suggested by Joe and Matthew, is better than looping.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.32108 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO