如何按多条件过滤对象中的评论数组(排除指定状态)
过滤评论对象中的指定状态项
我有如下包含评论数据的对象:
const newComments = { commentDirectoryId: "ee63997c-01d5-ec11-8dad-e116bd673e14", comments: [ { id: "123", status: { entity: null, id: "1a913152-7809-ec11-8daa-90600b960f93", name: "In work", parentId: null, }, }, { id: "124", status: { entity: null, id: "1a913152-7809-ec11-8daa-90600b960f94", name: "Note", parentId: null, }, }, { id: "125", status: { entity: null, id: "1a913152-7809-ec11-8daa-90600b960f95", name: "Canceled", parentId: null, }, }, { id: "126", status: { entity: null, id: "1a913152-7809-ec11-8daa-90600b960f96", name: "Done", parentId: null, }, }, ], dataType: "Tags", idAttributeApprovalName: "12-015-123", };
同时有一个过滤条件数组:
const values = ["Note", "Canceled", "Done"];
需求是保留comment.status.name不等于数组中任意值的评论,最终得到如下结构的对象:
const filteredResult = { commentDirectoryId: "ee63997c-01d5-ec11-8dad-e116bd673e14", comments: [ { id: "123", status: { entity: null, id: "1a913152-7809-ec11-8daa-90600b960f93", name: "In work", parentId: null, }, }, ], dataType: "Tags", idAttributeApprovalName: "12-015-123", };
解决方案
可以使用JavaScript的filter方法结合对象展开运算符实现,既不修改原对象,又能得到符合要求的结果:
const values = ["Note", "Canceled", "Done"]; const filteredComments = { // 复制原对象的所有属性 ...newComments, // 过滤comments数组,保留不在排除列表中的项 comments: newComments.comments.filter(comment => !values.includes(comment.status.name)) };
说明
- 对象展开运算符
...newComments会把原对象的commentDirectoryId、dataType等属性全部复制到新对象中; filter方法遍历原comments数组,!values.includes(comment.status.name)判断当前评论的状态名称是否不在排除列表里,符合条件的项会被保留到新数组中;- 最终得到的
filteredComments就是需求中的目标对象。
内容的提问来源于stack exchange,提问作者ko1p
相关产品推荐
相关产品推荐

