.map& .slice数据集中的唯一值

时间:2018-05-20 16:20:40

标签: javascript reactjs lodash

我有很多玩家信息。我把球员拉到了前端。我已设法映射它们并将它们切片以带回前11名玩家。请参阅下面的代码。我现在只想从一个独特的位置(值)带回球员。

<script async src="https://cdn.ampproject.org/v0.js"></script>
<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>
<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.1.js"></script>
<script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>

<amp-state id="jsonData">
<script type="application/json">
  {
    "key": "a",
    "a": {"items": [{"name": "mercedes"},{"name": "bmw"}]},
    "b": {"items": [{"name": "sandal"},{"name": "red shoes"}]},
    "c": {"items": [{"name": "novel"},{"name": "comic"}]},
    "d": {"items": [{"name": "rice"},{"name": "mie"}]}
  }
  </script>
</amp-state>

<form method="GET" class="p2" action="/" target="_top">
  <div class="ampstart-input form-elem">
    <label for="sel1" class="form-label">Select1</label>
    <select name="sel1" id="sel1" on="change:AMP.setState({jsonData: {key : event.value}})">
      <option value="a">car</option>
      <option value="b">shoes</option>
      <option value="c">book</option>
      <option value="d">food</option>
    </select>
  </div>
  <div class="ampstart-input form-elem">
    <amp-list [src]="jsonData[jsonData.key]" items="." layout="fixed-height" width="auto" height="25">
      <template type="amp-mustache">
        <label for="sel2" class="form-label">Select2</label>
        <select name="sel2" id="sel2">
          {{#items}}
            <option>{{name}}</option>
          {{/items}}
        </select>
      </template>
    </amp-list>
  </div>
</form>

我想带回最多11名玩家,但每个 render() { const { players } = this.props; const { primaryPositionNumber, image, fullName, playerId } = players; const playerPositions = this.props.players.slice(0, 11).map(function(player) { return ( <Chip className="player" data-position={player.primaryPositionNumber} avatar={<Avatar alt={player.fullName} src={`${player.image}.png`}/>} label={player.fullName} key={player.playerId} /> ); }); return <div> {playerPositions} </div> } 值只有一名玩家。因此,我最终会有11名球员处于不同的位置。我正在使用es6,lodash并做出反应,如果这些在这里有用吗?

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
const players = [
  {
    number: 1,
    name: 'Timmy'
  },
  {
    number: 2,
    name: 'Bob'
  },
  {
    number: 2,
    name: 'Rob'
  },
  {
    number: 1,
    name: 'Ryan'
  }
];

const playerNumbers = [1,2];

const filteredPlayers = playerNumbers.map(n => players.find(f => n === f.number));
console.log(filteredPlayers);
&#13;
&#13;
&#13;

作为一个例子,我假设您只需要通过playerNumbers过滤玩家。 players.find将返回遇到的第一个。