skip to Main Content

So it’s a social media comments thing, with two parent comments, and comment#2 has two child comments.

[
{
    "id": 1,
    "content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
    "createdAt": "1 month ago",
    "score": 12,
    "user": {
        "image": {
            "png": "./images/avatars/image-amyrobson.png",
            "webp": "./images/avatars/image-amyrobson.webp"
        },
        "username": "amyrobson"
    },
    "replies": []
},
{
    "id": 2,
    "content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
    "createdAt": "2 weeks ago",
    "score": 5,
    "user": {
        "image": {
            "png": "./images/avatars/image-maxblagun.png",
            "webp": "./images/avatars/image-maxblagun.webp"
        },
        "username": "maxblagun"
    },
    "replies": [
        {
            "id": 3,
            "content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
            "createdAt": "1 week ago",
            "score": 4,
            "replyingTo": "maxblagun",
            "user": {
                "image": {
                    "png": "./images/avatars/image-ramsesmiron.png",
                    "webp": "./images/avatars/image-ramsesmiron.webp"
                },
                "username": "ramsesmiron"
            }
        },
        {
            "id": 4,
            "content": "I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.",
            "createdAt": "2 days ago",
            "score": 2,
            "replyingTo": "ramsesmiron",
            "user": {
                "image": {
                    "png": "./images/avatars/image-juliusomo.png",
                    "webp": "./images/avatars/image-juliusomo.webp"
                },
                "username": "juliusomo"
            }
        }
    ]
}

]

I’m trying to figure out how to delete a child comment and return the array in the same parent>child set up.

Right now, on clicking the delete button on a comment I run a function that loops through the parent comments to filter out any parent comment that matches the ID of the comment that was clicked

    let filteredComments = [];

function handleClick(e) {
    setLoading(true);
    for (let i = 0; i < comments.length; i++) {
        if (comments[i].id !== Number(e.target.id)) {
            filteredComments = [...filteredComments, comments[i]];
        }
    }

    console.log(filteredComments);
    // setComments(...comments, filteredComments);
    setTimeout(() => {
        setLoading(false);
    }, 1000);
}

And that returns the an identical array to the original data.json comments from way up above. The comment I’m trying to delete is id4 and is a child comment. I’ve tried a dozen different ways to loop through the child comments but I can’t figure out how to only return child comments that don’t match the selected comment id and return the object in the same parent>child way (at one point I got it to return an array with the child comment right next to the parent comments which would mess up mapping the comments to the page).

The last thing I tried was looping through the parent comments, pushing those to the filtered array, then loop through the child comments of any comments within the filtered array.

    let filteredComments = [];

function handleClick(e) {
    setLoading(true);
    for (let i = 0; i < comments.length; i++) {
        if (comments[i].id !== Number(e.target.id)) {
            filteredComments = [...filteredComments, comments[i]];
        }
    }


    if (comments[i].replies.length !== 0) {
        for (let k = 0; k < comments[i].replies.length; k++) {
            if (comments[i].replies[k].id !== Number(e.target.id)) {
                filteredComments = [
                    ...filteredComments,
                    comments[i].replies[k],
                ];
            }
        }
    }

    console.log(filteredComments);
    // setComments(...comments, filteredComments);
    setTimeout(() => {
        setLoading(false);
    }, 1000);
}

2

Answers


  1. I assume you are only using this to delete comments, and that there is only one level of replies.

    All you need to do is locate the replies array and find the matching index within that array that requires deleting. Then use splice to delete it.

    reduce is used to find a match, and return the replies and index when the match is found. The accumulator a is set to the match, or if no match is found, the accumulator is unaltered.

    const data = [{"id":1,"content":"Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.","createdAt":"1 month ago","score":12,"user":{"image":{"png":"./images/avatars/image-amyrobson.png","webp":"./images/avatars/image-amyrobson.webp"},"username":"amyrobson"},"replies":[]},{"id":2,"content":"Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!","createdAt":"2 weeks ago","score":5,"user":{"image":{"png":"./images/avatars/image-maxblagun.png","webp":"./images/avatars/image-maxblagun.webp"},"username":"maxblagun"},"replies":[{"id":3,"content":"If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.","createdAt":"1 week ago","score":4,"replyingTo":"maxblagun","user":{"image":{"png":"./images/avatars/image-ramsesmiron.png","webp":"./images/avatars/image-ramsesmiron.webp"},"username":"ramsesmiron"}},{"id":4,"content":"I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.","createdAt":"2 days ago","score":2,"replyingTo":"ramsesmiron","user":{"image":{"png":"./images/avatars/image-juliusomo.png","webp":"./images/avatars/image-juliusomo.webp"},"username":"juliusomo"}}]}]
    
    const idToDelete = 4
    
    const {replies, index} = data.reduce((a, {replies}, index) => (
      index = replies.findIndex(({id}) => id===idToDelete), 
      index!==-1 ? {replies, index} : a), undefined)
    
    replies.splice(index, 1)
    
    console.log(data)
    Login or Signup to reply.
  2. In case there’s a deeper level of replies (I added comment ID:5), this code should recursively handle the deletion:

    const comments = [{
        "id": 1,
        "content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
        "createdAt": "1 month ago",
        "score": 12,
        "user": {
          "image": {
            "png": "./images/avatars/image-amyrobson.png",
            "webp": "./images/avatars/image-amyrobson.webp"
          },
          "username": "amyrobson"
        },
        "replies": []
      },
      {
        "id": 2,
        "content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
        "createdAt": "2 weeks ago",
        "score": 5,
        "user": {
          "image": {
            "png": "./images/avatars/image-maxblagun.png",
            "webp": "./images/avatars/image-maxblagun.webp"
          },
          "username": "maxblagun"
        },
        "replies": [{
            "id": 3,
            "content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
            "createdAt": "1 week ago",
            "score": 4,
            "replyingTo": "maxblagun",
            "user": {
              "image": {
                "png": "./images/avatars/image-ramsesmiron.png",
                "webp": "./images/avatars/image-ramsesmiron.webp"
              },
              "username": "ramsesmiron"
            }
          },
          {
            "id": 4,
            "content": "I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.",
            "createdAt": "2 days ago",
            "score": 2,
            "replyingTo": "ramsesmiron",
            "user": {
              "image": {
                "png": "./images/avatars/image-juliusomo.png",
                "webp": "./images/avatars/image-juliusomo.webp"
              },
              "username": "juliusomo"
            },
            "replies": [{
              "id": 5,
              "content": "Even deeper comment",
              "replyingTo": "juliusomo",
              "createdAt": "3 month ago",
              "score": 80,
              "user": {
                "image": {
                  "png": "./images/avatars/image-somebody.png",
                  "webp": "./images/avatars/image-somebody.webp"
                },
                "username": "somebody"
              },
              "replies": []
            }]
          }
        ]
      }
    ]
    
    
    
    function deleteComment(id, arr) {
      arr.forEach(function(item, index) {
        if (item.id == id) {
          arr.splice(index, 1)
        } else if (item.replies && item.replies.length > 0) {
          deleteComment(id, item.replies)
        }
      })
    }
    
    deleteComment(5, comments)
    
    console.log(comments)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search