Як побудувати дерево коментарів з масиву?

To build a comment tree from an array, you can follow these steps:

  1. Create an empty object to store the comment tree.
  2. Loop through the array of comments.
  3. For each comment, check if there is a "to_comment_id" property. If not, it is a root comment, so add it directly to the comment tree object.
  4. If there is a "to_comment_id" property, find the corresponding parent comment in the comment tree object.
  5. Add the current comment as a child of the parent comment.
  6. Repeat steps 4-5 until all comments are processed.

Here is an example implementation in JavaScript:

// Example comment array
const comments = [
  { id: 1, to_comment_id: null },
  { id: 2, to_comment_id: 1 },
  { id: 3, to_comment_id: 2 },
  { id: 4, to_comment_id: 3 },
  { id: 5, to_comment_id: 4 },
  { id: 6, to_comment_id: 5 },
  { id: 7, to_comment_id: null },
  { id: 8, to_comment_id: 7 },
  { id: 9, to_comment_id: 8 },
  { id: 10, to_comment_id: 9 },
  { id: 11, to_comment_id: 10 },
];

// Function to build comment tree
function buildCommentTree(comments) {
  const commentTree = {};

  comments.forEach((comment) => {
    const { id, to_comment_id } = comment;

    if (to_comment_id === null) {
      // This is a root comment
      commentTree[id] = { comment, children: [] };
    } else {
      // Find the parent comment
      const parentComment = findParentComment(commentTree, to_comment_id);

      if (parentComment) {
        parentComment.children.push({ comment, children: [] });
      }
    }
  });

  return commentTree;
}

// Function to find parent comment in the comment tree
function findParentComment(commentTree, to_comment_id) {
  for (const key in commentTree) {
    if (commentTree.hasOwnProperty(key)) {
      const parentComment = commentTree[key];

      if (parentComment.comment.id === to_comment_id) {
        return parentComment;
      }

      const childComment = findParentComment(parentComment.children, to_comment_id);
      if (childComment) {
        return childComment;
      }
    }
  }

  return null;
}

// Example usage
const commentTree = buildCommentTree(comments);

console.log(commentTree);

This implementation will create a comment tree object where each comment is a child of its parent comment. You can then use this object to generate the HTML structure using the UL and LI tags as desired.

BotAI · 7 місяців тому
Коментарі (0)

    Ще немає коментарів

Щоб залишити коментар необхідно авторизуватися.

Вхід / Реєстрація