简体   繁体   English

如何在Reactjs中进行映射和过滤

[英]How to Map and Filter in Reactjs

carModel:
          [
           {_id : A, title : 2012},
           {_id : B, title : 2014}
          ],

car:      [{
            color    :'red',
            carModel : B //mongoose.Schema.ObjectId
           },
           {
            color    :'black',
            carModel : B //mongoose.Schema.ObjectId
           }     
          ]      

Here i add carModel ID on car's carModel and trying to filter on my react page 在这里我在汽车的carModel上添加carModel ID并尝试在我的反应页面上进行过滤

car.map(item=> 
              <p>{item.color}</p>
              <p>{carModel.map(model=> model.filter(model._id == item.carModel ? model.title : null)}
       )

I want to show carModel on page, here above code is not working and i believe this is not an exact method to do this, please rectify me 我想在页面上显示carModel,这里上面的代码不起作用,我相信这不是执行此操作的确切方法,请纠正我

You can use following: 您可以使用以下内容:

car.map(item=> {
  const filteredModels = carModel.filter(model => model._id === item.carModel);
  return (
    <div>
      <p>{item.color}</p>
      {filteredModels.map(model => <p>{model.title}</p>)}
    </div>
  );      
})

You need to return your elements like this to make it work. 您需要像这样return您的元素以使其起作用。 Also wrapping your elements with a div or something 还用div或其他东西包装元素

car.map(item=> 
  return (<div>
    <p>{item.color}</p>
    <p>{carModel.map(model=> model.filter(model._id == item.carModel ? model.title : null)}
   </div>)
)

filter method callback parameter is a function and you need to return one element in map function, so; filter方法的callback参数是一个函数,您需要在map函数中返回一个元素,因此;

car.map(item=> {
  return (<div>
    <p>{item.color}</p>
      {carModel.filter(model => model._id === item.carModel).map(model => <p>{model.title}</p>)}
  </div>);
})
car.map(item=> {
  return (
    <p>{item.color}</p>
    {
      carModel.filter(model => model._id === item.carModel)
      .map(m => <p>{m.title}</p>)
    }
  );      
})

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

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