json - 过滤和映射并保持原始
问题描述
我有以下结构:
this.pronos = [{
"id": 1,
"eventname": "EVENT1",
"round": "EVENT1-1",
"factor": 1,
"matchPassed": 10,
"matchs": [{
"eq1": "EQ1",
"eq2": "EQ2",
"scoreEq1": 0,
"scoreEq2": 3,
"passed": true,
"stats": {
"domicile": 35.29,
"exterieur": 35.29,
"nul": 29.41,
"boosted": 1
},
"date": 20190809,
"friendlyDate": "Vendredi 9 ao\u00fbt 2019 20:45",
"pronos": [{
"matchId": 10,
"userId": 1,
"username": "Marcel",
"points": 0,
"validation": true,
"pronoEq1": 1,
"pronoEq2": 0,
"booster": 0,
"MR": 0
},
...
]
},
...
],
},
...
]
我想保留原始数组并返回这个过滤和映射的数组。
getNextPronos() {
return this.pronos.filter(event => {
return event.matchs
.some(match => {
return match.date >= this.recentDate;
});
})
.map(event => {
event.matchs = event.matchs.filter(match => {
return match.date >= this.recentDate;
});
return event;
}).filter((event) => {
return event.matchs.length > 0;
});
}
我不想声明新数组,因为this.pronos
稍后会修改。
解决方案
如果我对您的理解正确,那么您目前的问题是您正在修改event
对象,但您想让它们保持不变。如果是这样:
getNextPronos() {
return this.pronos
// Only events where at least one match is after the date
.filter(({matchs}) => matchs.some(({date}) => date >= this.recentDate))
// Map to new event objects with filtered `matchs`
.map(event => ({
...event,
matchs: event.matchs.filter(({date}) => date >= this.recentDate)
}));
}
这会通过一个部分循环matchs
来查看是否有任何匹配在日期之后,然后再进行第二个完整循环以过滤掉日期之前的匹配。这对我来说似乎很好。另一种方法是在过滤掉一些事件之前为所有事件创建新的事件对象,如下所示:
getNextPronos() {
return this.pronos
// Map to new event objects with filtered `matchs`
.map(event => ({
...event,
matchs: event.matchs.filter(({date}) => date >= this.recentDate)
}))
// Filter out the (new) events that have no `matchs`
.filter(({matchs}) => matchs.length);
}
旁注:“match”的复数形式是“matches”(带有“e”)。