对数组中的数组进行排序



我有以下数组结果:

例:

[
{
id: "1",
league: {
name: "World Club Friendlies",
team: "Simple 1 & Simple 2"
}
},
{
id: "2",
league: {
name: "Senegal Ligue 2",
team: "Simple"
}
},
{
id: "3",
league: {
name: "World Club Friendlies",
team: "Simple 3 & Simple 4"
}
},
]

第一第三联赛的名称相似

上面的代码输出如下所示:

联赛名称:世界俱乐部友谊赛/球队:简单1和简单2

联赛名称:塞内加尔 法甲 2/球队名称:简单

联赛名称:世界俱乐部友谊赛/球队:简单3和简单4

现在我需要打印以下结果:

联赛名称:世界俱乐部友谊赛/球队:简单1和简单2和简单3和简单4

联赛名称:塞内加尔 法甲 2/球队名称:简单

我有这样的代码:

foreach($content as $result){
echo $result['league']['name'];
echo $result['team'];
}

使用reduce并检查team name作为键,并应用所需的条件,如下所示:

var data = [{
id: "1",
league: {
name: "World Club Friendlies",
team: "Simple 1 & Simple 2"
}
},
{
id: "2",
league: {
name: "Senegal Ligue 2",
team: "Simple"
}
},
{
id: "3",
league: {
name: "World Club Friendlies",
team: "Simple 3 & Simple 4"
}
},
]
var res = data.reduce((acc, curr) => {
if (acc[curr.league.name]) {
acc[curr.league.name] = {
name: curr.league.name,
team: acc[curr.league.name].team + " & " + curr.league.team
}
} else {
acc[curr.league.name] = {
name: curr.league.name,
team: curr.league.team
}
}
return acc;
}, {});
for (data in res) {
console.log("League name: " + res[data].name + "/Team:" + res[data].team)
}

相关内容

  • 没有找到相关文章

最新更新