JavaScript中匹配ID后向数组推送值的实现方法
Add a New Reply to a Comment by Matching Its ID
Got it, let's walk through how to solve this. You need to locate a specific comment using its id value, then push a new reply into its associated reply array. Here's a straightforward JavaScript solution tailored to your JSON structure:
Step-by-Step Implementation
First, let's work with your existing comments array, then create a reusable function to handle adding replies:
// Your original comments data const comments = [ { "id": "1", "root_id": "1", "target_id": "12", "text": "Hello World!", "comment_posted_by": "John", "comment_posted_by_image": "/../../assets/images/no-user.png", "comment_time": "2 mins ago", "reply": [ { "id": "123", "root_id": "1", "target_id": "222", "text": "Nice!" }, { "id": "124", "root_id": "1", "target_id": "222", "text": "Good!" } ] }, { "id": "2", "root_id": "2", "target_id": "12", "text": "Another comment example..." // Note: We'll handle cases where a comment might not have a `reply` array yet } ]; // Function to add a reply to the comment with a specific id function addReply(commentId, newReply) { // Find the target comment by matching its id const targetComment = comments.find(comment => comment.id === commentId); if (targetComment) { // Ensure the `reply` array exists (in case the comment didn't have one initially) if (!targetComment.reply) { targetComment.reply = []; } // Push the new reply into the array targetComment.reply.push(newReply); console.log(`Successfully added reply to comment #${commentId}`); } else { console.log(`Oops, no comment found with id: ${commentId}`); } } // Example: Add a new reply to comment with id "1" const myNewReply = { "id": "125", "root_id": "1", "target_id": "222", "text": "Love this post!" }; // Call the function addReply("1", myNewReply); // Verify the result (check the first comment's reply array) console.log(comments[0].reply);
Key Details:
Array.find(): This method efficiently searches the comments array and returns the first comment whoseidmatches your target. If no match is found, it returnsundefined.- Safety Check for
replyArray: We make sure thereplyproperty exists before pushing to it—this prevents errors if some comments don't have replies initially. - Reusable Function: The
addReplyfunction can be called anytime you need to add a new reply to any comment by just passing the comment ID and the new reply object.
If you need to handle nested replies (replies to replies), let me know and we can adjust the solution, but based on your provided structure, this should cover your use case perfectly.
内容的提问来源于stack exchange,提问作者hkaur13
相关产品推荐
相关产品推荐

