I'm trying to carry out some flatmapping and filtering on an array of objects, however, I'm not sure why my final result - after filtering, is still displaying the same number of objects where in some of them, the events
property has an empty array.
Object to handle (res) variable:
[
{
logs: [
{
events: [
{
"type": "unbond",
...
},
{
"type": "delegate",
...
},
{
"type": "someOther",
...
},
{
"type": "withdraw_rewards",
...
},
{
"type" : "someOtherOther",
...
},
...
]
}
timestamp: "someDate"
},
{
logs: [
{
events: [
{
"type": "withdraw_commission",
...
},
{
"type": "someOtherOtherOther",
...
},
{
"type": "someOther",
...
},
{
"type": "withdraw_rewards",
...
},
{
"type" : "someOtherOther",
...
},
...
]
}
timestamp: "someDate"
},
...
]
Result (after item 5, eveything has an empty array in the event_logs
prop:
[
{
timestamp: "somedate1",
event_logs: [
{
...
}
]
},
{
timestamp: "somedate2",
event_logs: [
{
...
}
]
},
{
timestamp: "somedate3",
event_logs: [] //empty
},
...
]
Here is the code I used to carry out the flatmapping and filtering:
const evnts = res.data.tx_responses.map(({timestamp, logs}) => ({
timestamp,
event_logs: logs.flatMap(log => log.events)
.filter(events => events.type === "delegate" || events.type === "withdraw_rewards" || events.type === "withdraw_commission" || events.type === "unbond")
}));
return evnts;
How can I get rid of those objects with an empty event_logs
prop?
You are creating a map of all but not filtering it in the resultant. if you want to remove evens that does not have any event_log in them you can filter them as shown.
const evnts = res.data.tx_responses.map(({timestamp, logs}) => ({
timestamp,
event_logs: logs.flatMap(log => log.events)
.filter(events => events.type === "delegate" || events.type === "withdraw_rewards" || events.type === "withdraw_commission" || events.type === "unbond")
}));
//filter here
evnts = evnts.filter(event => event.event_logs.length > 0 )
return evnts;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.