JSFiddle - React, Tailwind, and code Playground
by someprimetime
JavaScript
var comments = [
{ submission_id: '51901ea22db96b057f000025',
comment: 'Tsdfasdfasdfsadf',
user_id: '516b45f8ac6a1b488e000001',
username: 'testing',
_id: '51a290fe065e5153080006a7',
deleted: false,
reply: false,
created: 'Sun May 26 2013 15:47:26 GMT-0700 (PDT)',
parent_id: '51a290f6065e51530800068d' },
{ submission_id: '51901ea22db96b057f000025',
comment: 'Testing man Not sure',
user_id: '516b45f8ac6a1b488e000001',
username: 'testing',
_id: '51a290f6065e51530800068c',
deleted: false,
reply: false,
created: 'Sun May 26 2013 15:47:18 GMT-0700 (PDT)',
parent_id: '51a290f6065e51530800068d' },
{ submission_id: '51901ea22db96b057f00003d',
comment: 'Testing man Not sure',
user_id: '516b45f8ac6a1b488e000001',
username: 'testing',
_id: '51a290f6065e51530800068d',
deleted: false,
reply: false,
created: 'Sun May 26 2013 15:47:18 GMT-0700 (PDT)',
parent_id: null },
];
var childComments = [],
parentComments = [],
threadedComments = [];
comments.forEach(function(comment) {
if (comment.parent_id) {
// get child comments and put them in another array
childComments.push(comment);
} else {
parentComments.push(comment);
}
});
childComments.forEach(function(childComment, index) {
parentComments.forEach(function(parentComment) {
if (childComment.parent_id === parentComment._id) {
threadedComments.push(childComment);
parentComment['commentTree'] = threadedComments;
}
});
});
console.log(parentComments);