//array
let posts = [{
text: "First post!",
id: "p1",
comments: [{
id: "c1",
text: "First comment on first post!"
},
{
id: "c2",
text: "Second comment on first post!!"
},
{
id: "c3",
text: "Third comment on first post!!!"
}
]
},
{
text: "Aw man, I wanted to be first",
id: "p2",
comments: [{
id: "c4",
text: "Don't wory second poster, you'll be first one day."
},
{
id: "c5",
text: "Yeah, believe in yourself!"
},
{
id: "c6",
text: "Haha second place what a joke."
}
]
}
]
//loops
const removeComment = function(postId, commentID) {
for (let post in posts) {
if (posts[post].id == postId) {
for (let Comment of posts.comments) {
if (posts.comments[comment].id == commentID) {
comment.splice(comment, 1)
}
}
}
}
}
//invoking the function
tweeter.removeComment("p2", "c6")
I’m trying to reach a comment (I.e ‘c6’) in a specific post (i.e ‘p2’), and delete it from the array.
In order to go through the Comments objects I wrote a for if nested in for-if; I don’t get any error, but the first for-if is working fine. Thanks
There are a couple of things that you will need to change in your function. You are using let post in posts
which gives number in loop so your logic is off when you are trying to access it as object.
let Comment of posts.comments
You would want to loop through the specific comment with the matching postId.
You are using an undefined comment
. Check below snippet, run it and edit it as necessary.
let posts = [{
text: "First post!",
id: "p1",
comments: [{
id: "c1",
text: "First comment on first post!"
},
{
id: "c2",
text: "Second comment on first post!!"
},
{
id: "c3",
text: "Third comment on first post!!!"
}
]
},
{
text: "Aw man, I wanted to be first",
id: "p2",
comments: [{
id: "c4",
text: "Don't wory second poster, you'll be first one day."
},
{
id: "c5",
text: "Yeah, believe in yourself!"
},
{
id: "c6",
text: "Haha second place what a joke."
}
]
}
]
//loops
const removeComment = (postId, commentID)=> {
for (let post of posts) {
if (post['id'] == postId) {
for (let Comment of post.comments) {
if (Comment['id'] == commentID) {
post.comments.splice(post.comments.indexOf(Comment),1);
}
}
}
}
}
removeComment("p2","c6");
console.log(posts);