Home > Back-end >  How can I filter Array based if Key in object exists?
How can I filter Array based if Key in object exists?

Time:09-20

I have some code that filters data based on some keys. In this case it's bounced or opened. For my bounced part it works fine as if I want to show the bounced items it has a key of bounce and it's true. But the opened only exists if the message was opened, and value is true. I am wondering how I could filter based on my below code to get all items where the key item.opened does not exist or the value of it is false.

showBounceOnly(data) {
    if (this.showbounce !== true) {
        data = data.filter(item => item.bounce !== true)
    }
    if (this.showopened !== true) {
    data = data.filter(item => item.opened !== true)
    }
    this.dataSource = new MatTableDataSource(data);
}

Below is some sample data so based on that sample i would only want to return the last item in array as it does not have a opened key or it is false

 [{
                    "activityDate": "2022-09-18T21:21:06.035Z",
                    "email": [
                        "[email protected]"
                    ],
                    "opened": true,
                    "track_request": "track_request::a89a9305-1f53-4175-a6cd-5416b3ebd891",
                    "tracking_nbr": "R_B0PcrD5B"
                },
                {
                    "activityDate": "2022-09-18T21:20:45.674Z",
                    "bounce": true,
                    "email": [
                        "[email protected]"
                    ],
                    "track_request": "track_request::3a82bb14-f59b-4d61-a39f-636b46446261",
                    "tracking_nbr": "WR10YIimW"
                },
                {
                    "activityDate": "2022-09-18T21:20:51.398Z",
                    "email": [
                        "xxxxxxxxxyahoo.com"
                    ],
                    "track_request": "track_request::c4bac227-9ea8-45bf-806f-1ac475682764",
                    "tracking_nbr": "XiA3n80oCV"
                }]

CodePudding user response:

If I understood the question correctly, then the answer looks like this.

There is no item.opened or it has the value false

if (this.showopened !== true) {
  data = data.filter(item => !item.opened || item.opened !== true )
}

UPD: can shorten the code to

if (this.showopened !== true) {
   data = data.filter(item => !item.opened)
}
  • Related