繁体   English   中英

如何根据特定的动态属性过滤反应中的对象数组?

[英]How to filter an array of objects in react based on a specific dynamic property?

我正在调用 API 并获取数据。

0: {team: {…}, league: {…}, games: {…}, substitutes: {…}, shots: {…}, …}
1: {team: {…}, league: {…}, games: {…}, substitutes: {…}, shots: {…}, …}
2: {team: {…}, league: {…}, games: {…}, substitutes: {…}, shots: {…}, …}
3: {team: {…}, league: {…}, games: {…}, substitutes: {…}, shots: {…}, …}
4: {team: {…}, league: {…}, games: {…}, substitutes: {…}, shots: {…}, …}

现在我想做的是映射这个对象数组,并在一个对象数组中使用相同的团队过滤它,而在另一个对象数组中使用其他团队。

0:
cards: {yellow: 2, yellowred: 0, red: 0}
dribbles: {attempts: 9, success: 5, past: null}
duels: {total: 113, won: 58}
fouls: {drawn: 9, committed: 16}
games: {appearences: 23, lineups: 11, minutes: 1007, number: null, position: 'Attacker', …}
goals: {total: 8, conceded: 0, assists: 3, saves: null}
league: {id: 135, name: 'Serie A', country: 'Italy', logo: 'https://media.api-sports.io/football/leagues/135.png', flag: 'https://media.api-sports.io/flags/it.svg', …}
passes: {total: 414, key: 23, accuracy: 13}
penalty: {won: null, commited: null, scored: 0, missed: 1, saved: null}
shots: {total: 42, on: 20}
substitutes: {in: 12, out: 4, bench: 14}
tackles: {total: null, blocks: 1, interceptions: 3}
team: {id: 489, name: 'AC Milan', logo: 'https://media.api-sports.io/football/teams/489.png'}
[[Prototype]]: Object

每个团队都有不同的 ID。 而且由于我事先不知道团队的ID,因此我不知道如何过滤它。 一切都是动态的,即使是 id。

 var _ = require('lodash'); list = [ {check: 1 , team: {id: 489, name: 'AC Milan'} }, { check: 1 , team: {id: 489, name: 'AC Milan1'} }, { check: 1 , team: {id: 489, name: 'AC Milan1'} }, { check: 2 , team: {id: 489, name: 'AC Milan3'}}, { check: 2 , team: {id: 489, name: 'AC Milan2'}}, { check: 3 , team: {id: 489, name: 'AC Milan5'}}, { check: 5 , team: {id: 489, name: 'AC Milan3'}}, { check: 5 , team: {id: 489, name: 'AC Milan7'} } ] test = _.groupBy(list, "team.name"); console.log(test)

以下是我如何分解这些类型的问题。

  1. 是减少还是映射? 当结果可以/必须键入时,前者为真。
  2. 什么喂食(1)?

我的第一个猜测是你有一组团队提供的减少。

归约是一个类似于 (array, {}) -> { key: value } 的函数

该数组具有创建键和值的信息。

数组:原始数据

keyFromRawFn:

rawData => rawData.team.id

valueFromRawFn:

rawData => a record as described in your result

所以,减少将是,

rawDatas.reduction((newObj, rawData) => {
   const key = keyFromRawFn(rawData);
   const value = valueFromRawFn(rawData);
   newObj[key] = value;
   return newObj;
}, {});

这假定 rawDatas 的数组长度 = 团队数。 似乎是一个合理的第一个猜测,因为每个“团队”都有“游戏”。

如果不是,这仍然是一个有效的“核心”例程。 我们需要找出一个“预处理”来获得满足标准的 rawDatas。 该预处理将是一个以 id 为键的缩减,值是另一个缩减,它通过 preRawDatas 条目组合每个 preRawData(如果计数使用 sum,或者如果它们都具有游戏数,则使用平均值,或者 game_count x 平均值的总和)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM