【问题标题】:How to filter array in object by few conditions如何通过几个条件过滤对象中的数组
【发布时间】:2023-02-07 02:26:52
【问题描述】:

我有一个带有 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"];

我的任务是只返回不等于键的 cmets:

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",
};

【问题讨论】:

  • 你试过什么了?

标签: javascript arrays sorting


【解决方案1】:

您可以将 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);

【讨论】:

    【解决方案2】:
    const filteredComments = {
       // copy all props into a new object
       ...newComments,
    
       // add filtered comments
       comments: newComments.comments.filter(comment =>
        !values.includes(comment.status.name)
       ),
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-27
      • 2021-07-05
      • 1970-01-01
      • 2019-09-15
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      相关资源
      最近更新 更多