0👍
✅
I would use the reduce function.
Im building an object where the id is the key and the value is the object.
When I already have the id inside (The second time i meet the same id), i push to lines the relevant values.
Finally i console log the values of the object which is your desired output.
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))
Source:stackexchange.com