javascript 如何用少量条件过滤对象中的数组

crcmnpdw  于 2023-02-07  发布在  Java
关注(0)|答案(2)|浏览(117)

我有这样一个对象与newComments:

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 !== "Note" | "Canceled" |"Done"

换句话说:

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,
      },
    },
  ],
  dataType: "Tags",
  idAttributeApprovalName: "12-015-123",
};
ha5z0ras

ha5z0ras1#

您可以将Array#filterArray#everyArray#includes结合使用。

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"];
newComments.comments = newComments.comments.filter(c => 
                        values.every(v => c.status.name !== v));
// or !values.includes(c.status.name) if no complex matching logic is required
console.log(newComments);
3qpi33ja

3qpi33ja2#

const filteredComments = {
   // copy all props into a new object
   ...newComments,

   // add filtered comments
   comments: newComments.comments.filter(comment =>
    !values.includes(comment.status.name)
   ),
}

相关问题