NodeJS中如何访问双层方括号内的数据并根据评论ID更新评论状态
问题原因
你在CommentCreated事件中往comment字段存入的是索引数组格式的评论数据,每个评论项的三个元素依次对应评论ID、评论内容、评论状态,没有id这类对象属性,因此comm.id读取结果为undefined。
解决方案1:不修改原有存储结构,调整查询和赋值逻辑
仅修改CommentUpdated分支的代码即可:
if(type === 'CommentUpdated'){ const {id,content,postId,status} = data; const post = posts[postId]; // 取数组第0位匹配评论ID const targetComment = post.comment.find(comm => comm[0] === id); // 先判断是否查到对应评论,避免报错 if(targetComment){ targetComment[1] = content; targetComment[2] = status; } }
解决方案2:更易维护的优化方案,修改存储为对象格式
只需要调整CommentCreated分支的存储逻辑,后续所有评论操作都可以直接通过属性读取,你原有CommentUpdated分支的comm.id写法可以直接生效:
if(type === 'CommentCreated'){ const {id,content,postId,status} = data; const post = posts[postId]; // 存储为对象而非数组,支持属性访问 post.comment.push({id, content, status}); }
内容的提问来源于stack exchange,提问作者jayasree
相关产品推荐
相关产品推荐

