通过匹配的对象键值将对象过滤为两组

时间:2017-08-04 17:23:18

标签: javascript reactjs

让我们说我有以下对象

var transformers = [
  {
    name: 'Optimus Prime',
    form: 'Freightliner Truck',
    team: 'Autobot'
  },
  {
    name: 'Megatron',
    form: 'Gun',
    team: 'Decepticon'
  },
  {
    name: 'Bumblebee',
    form: 'VW Beetle',
    team: 'Autobot'
  },
  {
    name: 'Soundwave',
    form: 'Walkman',
    team: 'Decepticon'
  }
];

如何根据team

渲染两个组
<div>
<h1>Autobot Team</h1>
... //Here goes the corresponding matches
</div>
<div>
<h1>Decepticon Team</h1>
... //Here goes the corresponding matches
</div>

我试了这个没有运气

renderTeam(){
  transformers.map(team =>{
   if(team.team === "Autobot"){
    return(
     <div>{team.name}</div>
    )
   }
   if(team.team === "Decepticon"){
    return(
     <div>{team.name}</div>
    )
   }
  })
}
<div>
 <h1>Autobot Team</h1>
  {this.renderTeam()}
</div>
<div>
 <h1>Autobot Team</h1>
  {this.renderTeam()}
</div>

2 个答案:

答案 0 :(得分:3)

你的函数renderTeam可以采用一个字符串参数,允许你过滤和映射数组:

renderTeam(team) {
  return transformers
    .filter(transformer => transformer.team === team)
    .map(transformer => (<div key={transformer.name}>{transformer.name}</div>);
}

render() {
  return (
    <div className="transformer-teams">
      <div>
        <h1>Autobot Team</h1>
        {renderTeam('Autobot')}
      </div>
      <div>
        <h1>Decepticon Team</h1>
        {renderTeam('Decepticon')}
      </div>
    </div>
  );
}

答案 1 :(得分:1)

要实现这一点,请将参数传递给包含任何一个团队名称的renderTeam方法,并返回ui元素。不要忘记从renderTeam方法返回结果。

还为循环内的每个元素指定唯一键

像这样:

<div>
    <h1>Autobot Team</h1>
    {this.renderTeam('Autobot')}
</div>
<div>
    <h1>Autobot Team</h1>
    {this.renderTeam('Decepticon')}
</div>

renderTeam(team){
    let items = [];
    transformers.forEach((item,i) => {
        if(item.team === team)
            items.push(<div key={i}>{item.name}</div>);         
    })
    return items;
}

但是使用这种方法你需要再次运行相同的循环,所以为了避免你也可以像这样写它:

renderTeam(){
    let team1 = [], team2 = [];
    transformers.forEach((item,i) => {
        if(item.team === 'Autobot')
            team1.push(<div key={i}>{item.name}</div>);
        else if(item.team === 'Decepticon')
            team2.push(<div key={i}>{item.name}</div>);
    })
    return (
        <div>
            <div>
                <h1>Autobot Team</h1>
                {team1}
            </div>
            <div>
                <h1>Autobot Team</h1>
                {team2}
            </div>
        </div>
    )

}

render(){
    return(
        <div>
            {this.renderTeam()}
        </div>
    )
}