我收到这样的数组:
[
{ league: {id: 2, name: "champions league"}, event: "psg - varsovia", scoreteam1: 1, scoreteam:2},
{ league: {id: 5, name: "world cup"} , event: "belgium - england", scoreteam1: 1, scoreteam:2},
{ league: {id: 2, name: "champions league"}, event: "madrid - fc bruge", scoreteam1: 3, scoreteam:2},
{ league: {id: 2, name: "champions league"}, event: "milan - dortmund", scoreteam1: 1, scoreteam:2},
{ league: {id: 5, name: "world cup"} , event: "japan - danemark", scoreteam1: 1, scoreteam:5}
]
,我想获得一个新的数组,其中将同一联盟的所有事件分组在一起。最好的方法是什么?
[
{
name: "champions league", id: 2,
events:
[
{"psg - varsovia", scoreteam1: 1, scoreteam:2},
{"milan - dortmund", scoreteam1: 1, scoreteam:2 },
{"madrid - fc bruge", scoreteam1: 3, scoreteam:2}
]
},
{
name: "world cup", id: 5,
events:
[
{"belgium - england", scoreteam1: 1, scoreteam:2},
{"japan - danemark", scoreteam1: 1, scoreteam:5}
]
}
]
我已经做到了,但是我认为它很冗长:
function compareCompetitionId(leagueId, item) {
return leagueId === item.competition.id;
}
function containCompetitionId(leagueId, items) {
return items.some(compareCompetitionId.bind(null, leagueId));
}
function groupByCompetitionId(memo, item) {
var leagueId = memo.filter(containCompetitionId.bind(null, item.competition.id));
if (leagueId.length > 0) {
leagueId[0].push(item);
} else {
memo.push([item]);
}
return memo;
}
// accumulateur
var results = list.reduce(groupByCompetitionId, []);
console.log(results)
答案 0 :(得分:1)
您需要遍历对象数组,然后检查每个对象的属性。
进行迭代时,您会发现是否已经添加了新对象(具有所需结构的对象)来寻找id
,如果是,则将事件添加到events
数组中,如果否,请创建一个新对象,然后将其推入所需的结果数组。
let arr = [
{ league: {id: 2, name: "champions league"}, event: "psg - varsovia", scoreteam1: 1, scoreteam:2},
{ league: {id: 5, name: "world cup"} , event: "belgium - england", scoreteam1: 1, scoreteam:2},
{ league: {id: 2, name: "champions league"}, event: "madrid - fc bruge", scoreteam1: 3, scoreteam:2},
{ league: {id: 2, name: "champions league"}, event: "milan - dortmund", scoreteam1: 1, scoreteam:2},
{ league: {id: 5, name: "world cup"} , event: "japan - danemark", scoreteam1: 1, scoreteam:5}
]
let resultArr = []
for (var obj of arr){
if (obj.hasOwnProperty("league")){
if (obj.league.hasOwnProperty("id") && obj.league.hasOwnProperty("name")){
let existObj = resultArr.find(x => x.id == obj.league.id)
if (existObj == null){
let newObj = {}
newObj.name = obj.league.name
newObj.id = obj.league.id
newObj.events = []
if (obj.hasOwnProperty("event")){
let event = {}
event.teams = obj.event;
event.scoreteam1 = obj.scoreteam1;
event.scoreteam2 = obj.scoreteam;
newObj.events.push(event)
}
resultArr.push(newObj)
}
else{
if (!existObj.hasOwnProperty("events")){
existObj.events = []
}
let event = {}
event.teams = obj.event;
event.scoreteam1 = obj.scoreteam1;
event.scoreteam2 = obj.scoreteam;
existObj.events.push(event)
}
}
}
}
console.log(resultArr)