gpt4 book ai didi

javascript - 从对象的嵌套数组中返回匹配的项目

转载 作者:行者123 更新时间:2023-11-28 16:49:30 25 4
gpt4 key购买 nike

我有按预定数据分组的数组,如下所示

[{
scheduledOn: "2020-02-05T00:00:00"
matches:
{id: 1, homeTeamName: "BLUE", homeTeamId: 1, homeScore: 1, awayTeamName: "Red", awayTeamId: 2, …}
{id: 2,homeTeamName: "Red", homeTeamId: 2, homeScore: 1, awayTeamName: "Yellow", awayTeamId: 3, …}
},
{
scheduledOn: "2020-01-06T00:00:00"
matches:
0: {id:3, homeTeamName: "BLUE", homeTeamId: 1, homeScore: 0, awayTeamName: "Yellow", awayTeamId: 3, …}
}]

我想返回一个与所选 ID 匹配的匹配对象(不是数组)

我尝试过的可能解决方案1:

matches.map(match => match.matches
.find(m => m.id === selectedId))

返回:

 [{

id: 1, homeTeamName: "BLUE", homeTeamId: 1, homeScore: 1, awayTeamName: "Red", awayTeamId: 2, …
}]

但我希望这只是一个对象而不是数组。

我尝试过的可能解决方案2:

matches.map(match => match.matches
.filter(m => m.id === selectedId))
.map(match => console.log(match

)

返回:

 [
{id: 1, homeTeamName: "BLUE", homeTeamId: 1, homeScore: 1, awayTeamName: "Red", awayTeamId: 2, …}
]

但这也以数组形式返回。

有没有办法可以匹配 id 对象而不是数组?

感谢您的帮助

最佳答案

您使用了 find() 两次

const matches = [{
scheduledOn: "2020-02-05T00:00:00",
matches:[
{id: 1, homeTeamName: "BLUE", homeTeamId: 1, homeScore: 1, awayTeamName: "Red", awayTeamId: 2 },
{id: 2,homeTeamName: "Red", homeTeamId: 2, homeScore: 1, awayTeamName: "Yellow", awayTeamId: 3 }]
},
{
scheduledOn: "2020-01-06T00:00:00",
matches:[{id:3, homeTeamName: "BLUE", homeTeamId: 1, homeScore: 0, awayTeamName: "Yellow", awayTeamId: 3 }]
}];


const selectedId = 3;
const required = matches.find(match =>
match.matches.find(m => m.id === selectedId));
console.log(required);

// if you wanted nested object, add another `.find()`
console.log(required .matches.find(m => m.id === selectedId));

关于javascript - 从对象的嵌套数组中返回匹配的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60099967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com