我在MongoDB中具有arr数据,需要将文档压缩为一个,以便可以在chartjs中显示数据。
arr = [
{
"_id": "5d7baef782e09dc7f6b5be2d",
"awaySpread": "3.0",
"homeSpread": "-3.0",
"homeTeam": "Tennessee Titans",
"awayId": "4529605_261_sp",
"awayTeam": "Indianapolis Colts",
"homeId": "4529605_262_sp",
"eventDate": "2019-09-15 13:00:00",
"createdDate": "2019-09-13T13:00:06.527Z"
},
{
"_id": "5d7baef782e09dc7f6b5be31",
"awaySpread": "-19.5",
"homeSpread": "19.5",
"homeTeam": "Miami Dolphins",
"awayId": "4529609_269_sp",
"awayTeam": "New England Patriots",
"homeId": "4529609_270_sp",
"eventDate": "2019-09-15 13:00:00",
"createdDate": "2019-09-13T13:00:06.527Z"
},
{
"_id": "5d7baef782e09dc7f6b5be2d",
"awaySpread": "2.5",
"homeSpread": "-2.5",
"homeTeam": "Tennessee Titans",
"awayId": "4529605_261_sp",
"awayTeam": "Indianapolis Colts",
"homeId": "4529605_262_sp",
"eventDate": "2019-09-15 13:00:00",
"createdDate": "2019-09-13T13:30:06.527Z"
}
]
希望将其引入:
newarr = [
{
"_id": "5d7baef782e09dc7f6b5be2d",
"awaySpread": "3.0",
"homeSpread": "-3.0",
"homeTeam": "Tennessee Titans",
"awayId": "4529605_261_sp",
"awayTeam": "Indianapolis Colts",
"homeId": "4529605_262_sp",
"eventDate": "2019-09-15 13:00:00",
"createdDate": "2019-09-13T13:00:06.527Z",
"lines": {
"spread": ["3.0","2.5"],
"dates: : ["2019-09-13T13:00:06.527Z","2019-09-13T13:30:06.527Z"]
},
},
{
"_id": "5d7baef782e09dc7f6b5be31",
"awaySpread": "-19.5",
"homeSpread": "19.5",
"homeTeam": "Miami Dolphins",
"awayId": "4529609_269_sp",
"awayTeam": "New England Patriots",
"homeId": "4529609_270_sp",
"eventDate": "2019-09-15 13:00:00"
"createdDate": "2019-09-13T13:00:06.527Z",
"lines": {
"spread": ["-19.5"],
"dates: : ["2019-09-13T13:00:06.527Z"]
},
}
]
我可以使用过滤器仅返回基于awayId的唯一对象,但是我不确定使用过滤器是否可以让我推送带有点差和日期的行。
答案 0 :(得分:0)
我会使用reduce函数。
我正在构建一个对象,其中id是键,而值是该对象。 当我已经有ID时(第二次我遇到相同的ID)时,我会按行插入相关值。
最后,我在控制台上记录了所需输出的对象的值。
arr = [
{
"_id": "5d7baef782e09dc7f6b5be2d",
"awaySpread": "3.0",
"homeSpread": "-3.0",
"homeTeam": "Tennessee Titans",
"awayId": "4529605_261_sp",
"awayTeam": "Indianapolis Colts",
"homeId": "4529605_262_sp",
"eventDate": "2019-09-15 13:00:00"
},
{
"_id": "5d7baef782e09dc7f6b5be31",
"awaySpread": "-19.5",
"homeSpread": "19.5",
"homeTeam": "Miami Dolphins",
"awayId": "4529609_269_sp",
"awayTeam": "New England Patriots",
"homeId": "4529609_270_sp",
"eventDate": "2019-09-15 13:00:00"
},
{
"_id": "5d7baef782e09dc7f6b5be2d",
"awaySpread": "2.5",
"homeSpread": "-2.5",
"homeTeam": "Tennessee Titans",
"awayId": "4529605_261_sp",
"awayTeam": "Indianapolis Colts",
"homeId": "4529605_262_sp",
"eventDate": "2019-09-15 13:00:00"
}
]
const newArr = arr.reduce((result, itr) => {
if (result[itr.awayId]) {
result[itr.awayId].lines.spread.push(itr.awaySpread)
result[itr.awayId].lines.dates.push(itr.eventDate)
} else {
result[itr.awayId] = { ...itr, lines: { spread: [itr.awaySpread], dates: [itr.eventDate] }}
}
return result
}, {})
console.log(Object.values(newArr))