DEV Community

Enrico Antonio Phie
Enrico Antonio Phie

Posted on

How to loop through array of objects with different length of key pair?

Hello Guys, I'm a newbie to javascript and i would like your help to solve this problem. I need to count the total of comment in this array. But the object in this array has different length of key pair. how do i looping through this array of object? Really appreciate any help, been stuck in this problem for hours.

const comments = [
    {
        commentId: 1,
        commentContent: 'Hai',
        replies: [
            {
                commentId: 11,
                commentContent: 'Hai juga',
                replies: [
                    {
                        commentId: 111,
                        commentContent: 'Haai juga hai jugaa'
                    },
                    {
                        commentId: 112,
                        commentContent: 'Haai juga hai jugaa'
                    }
                ]
            },
            {
                commentId: 12,
                commentContent: 'Hai juga',
                replies: [
                    {
                        commentId: 121,
                        commentContent: 'Haai juga hai jugaa'
                    }
                ]
            }
        ]
    },
    {
        commentId: 2,
        commentContent: 'Halooo'
    }
]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
potcode profile image
Potpot • Edited

update: one shot

function countComments(comments) {
  let count = 0;
  comments.forEach((comment) => {
    count++;
    const replies = comment.replies;
    if (replies) {
      count += countComments(replies);
    }
  });
  return count;
}

console.log(countComments(comments));
Enter fullscreen mode Exit fullscreen mode