【发布时间】:2021-03-11 09:00:46
【问题描述】:
我有一个非常复杂的问题,我似乎无法弄清楚。我有两个要合并分数的对象数组。它应该根据分数合并/附加某些属性。例如,在两个数组之间共有 4 个gameId,其中 3 个是唯一的。合并时,如果它与 gameId 相同,则应合并 _scores 部分,因此在这种情况下,它将是 EarthNormal 合并。但问题是有时_scores 中的score 可能有重复的分数,因此 BAR 和 BASH 看起来几乎完全相同但不同,它可以附加但 FOO 的分数在两者上完全相同,所以我不希望它合并到分数中(如果有意义的话)。
const arr1 = [{
"gameId": "AirNormal",
"_scores":
[{
"score": 144701,
"playerName": "FOO",
"fullCombo": true,
"timestamp": 1599968866
}]
}, {
"gameId": "EarthNormal",
"_scores":
[{
"score": 177352,
"playerName": "BAR",
"fullCombo": true,
"timestamp": 1599969253
}, {
"score": 164665,
"playerName": "FOO",
"fullCombo": false,
"timestamp": 1599970971
}]
}];
const arr2 = [{
"gameId": "EarthNormal",
"_scores":
[{
"score": 177352,
"playerName": "BASH",
"fullCombo": false,
"timestamp": 1512969017
}, {
"score": 164665,
"playerName": "FOO",
"fullCombo": false,
"timestamp": 1599970971
}]
}, {
"gameId": "FireNormal",
"_scores":
[{
"_score": 124701,
"_playerName": "FOO",
"_fullCombo": true,
"_timestamp": 1591954866
}]
}];
我希望最终的合并数组看起来像:
mergedArray = [{
"gameId": "AirNormal",
"_scores":
[{
"score": 144701,
"playerName": "FOO",
"fullCombo": true,
"timestamp": 1599968866
}]
}, {
"gameId": "EarthNormal",
"_scores":
[{
"score": 177352,
"playerName": "BAR",
"fullCombo": true,
"timestamp": 1599969253
}, {
"score": 177352,
"playerName": "BASH",
"fullCombo": false,
"timestamp": 1512969017
}, {
"score": 164665,
"playerName": "FOO",
"fullCombo": false,
"timestamp": 1599970971
}]
}, {
"gameId": "FireNormal",
"_scores":
[{
"score": 124701,
"playerName": "FOO",
"fullCombo": true,
"timestamp": 1591954866
}]
}]
我尝试过这样做并使用lodash:
let merged = [...arr1, ...arr2];
merged = _.uniqBy[merged, 'gameId']
let scoresMerge = _.uniqBy[merged, '_scores']
console.log(scoresMerge);
但它并没有像我预期的那样工作。我是不是在错误地处理这个问题?
【问题讨论】:
标签: javascript arrays ecmascript-6 lodash