gpt4 book ai didi

javascript - 如何根据Javascript中的嵌套值过滤数组

转载 作者:行者123 更新时间:2023-12-04 00:13:48 26 4
gpt4 key购买 nike

我有一个数组,我试图根据某个嵌套值进行过滤,而不获取任何其他元素。

const arrayData = [ 
{
country: "Country X",
games: [
{
gameTitle: 'Game1',
players: [{ name: 'John', status:'Active' },{ name: 'Rob', status:'Suspended' }]
},
{
gameTitle: 'Game2',
players: [{ name: 'Saly', status:'Blocked' }]
},
]
},
{
country: "Country Y",
games: [
{
gameTitle: 'Game1',
players: [{ name: 'Sindy', status:'Pending' },{ name: 'someone', status:'Rejected' }]
},
{
gameTitle: 'Game2',
players: [{ name: 'Alex', status:'New' },{ name: 'Nic', status:'Old' }]
},
]
},
];

我尝试过的:

let output = arrayData.filter(eachVal => { 
let opt = eachVal.games.some((
{ players }) => players
.some(({ status}) => status === 'Active'));
return opt;
})

查找具有 status 值的 所有玩家 的预期结果:'Active':

{ 
country: "Country X",
games: [
{
gameTitle: 'Game1',
players: [{ name: 'John', status:'Active' }]
}
]
}

但是结果:

[{"country":"Country X","games":[{"gameTitle":"Game1","players":[{"name":"John","status":"Active"},{"name":"Rob","status":"Suspended"}]},{"gameTitle":"Game2","players":[{"name":"Saly","status":"Blocked"}]}]}]

最佳答案

试试这个:

arrayData.map(({country, games: g}) => {

const games = g.map((g) => {
const players = g.players.filter((p) => p.status === 'Active')

return {...g, players}
})
.filter(({players}) => players.length > 0)

return {country, games}
}).filter(({games}) => games.length>0)

关于javascript - 如何根据Javascript中的嵌套值过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65643082/

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