I am trying to delete an object property. I used splice
method, also delete
method, but I receive “TypeError: Cannot delete property.”. I have a comments
array, whose each comment
object has replies
array of objects, and I am trying to delete one of the object (reply
object whose id is 1) inside replies
array. And then replacing this comment
object with its old version inside commments
array. I tried:
comments[localId].replies.splice(1, 1) // cannot delete property
comments[localId].replies = comments[localId].replies.filter((reply) => reply.id !== 1) // nothing changing unexpectedly
How can I handle this issue?
3
First, you need to confirm the property exists before trying to modify.
With Splice, check if the index exists first.
const comment = comments[localId];
const replyIndex = comment.replies.findIndex((reply) => reply.id === 1);
if (replyIndex !== -1) {
comment.replies.splice(replyIndex, 1);
}
With filter, be sure to check the validity of the Array
if (Array.isArray(comments[localId].replies)) {
comments[localId].replies = comments[localId].replies.filter((reply) => reply.id !== 1);
}
1