英文:
Map Through Array Condiotionally
问题
我在想,根据我所做的研究,我没有找到任何东西,但是否有一种方法可以有条件地映射一个对象数组。例如,我有一个包含医生预约信息的对象数组,我只想映射那些日期尚未过去的医生预约。
通常我会这样做,但这没有添加任何条件。
{doctorsApptData.map(apptData => (
<div>这个日期有效!{apptData.date}</div>
))}
我尝试过类似这样的方法,但没有成功。
{doctorsApptData.map(apptData => (
apptData.date >= DateTime.now() && (
<div>这个日期有效!{apptData.date}</div>
)))}
谢谢!
英文:
I am wondering, from the research I have done I have not found anything, but is there a way to conditionally map through an array of objects. For instance, I have an array of objects for doctors appointments and I am only wanting to map through the doctors appointments where the date has not past.
I normally do this, but this is not adding in any conditions.
{doctorsApptData.map(apptData => (
<div>This date is valid! {apptData.date}</div>
))}
I have tried something like this, but no luck
{doctorsApptData.map(apptData => (
apptData.date >= DateTime.now() && (
<div>This date is valid! {apptData.date}</div>
)))}
Thanks!
答案1
得分: 0
你可以在map
之前使用filter
方法。这个方法会创建一个只包含满足特定条件的元素的新数组。
例如:
{
doctorsApptData
.filter((apptData) => apptData.date >= DateTime.now())
.map((apptData) => <div>这个日期有效!{apptData.date}</div>);
}
英文:
You can use filter
method before map
. This method creates a new array with only the elements that meet a certain condition.
For example:
{
doctorsApptData
.filter((apptData) => apptData.date >= DateTime.now())
.map((apptData) => <div>This date is valid! {apptData.date}</div>);
}
答案2
得分: 0
当然,有几种方法。重要的是,我们正确理解在高阶函数的上下文中如何传递回调函数,因为排序函数如sort、map、filter等非常常用。
map()的工作原理如下:
```python
array.map((current, index) => {
// 这里可以放入你想要的逻辑
return (???)
}
所以在这种情况下,你可以这样做:
doctorsApptData.map((apptData, index) => {
if (apptData.date >= DateTime.now()){
return(
<div>这个日期是有效的! {apptData.date}</div>
)
}
)
或者如果你真的想使用三元运算符(个人建议不要过度使用它们,因为它们往往会影响代码的可读性):
doctorsApptData.map((apptData, index) => {
return(
apptData.date >= DateTime.now && (<div>这个日期是有效的! {apptData.date}</div>)
)
}
)
希望对你有所帮助!
<details>
<summary>英文:</summary>
Yeah sure, so there are a few ways. What's important is for us to correctly understand how passing in callbacks works in the context of higher order functions, since sorting functions like sort, map, filter etc are extremely commonly used.
map() works like this:
array.map((current, index) => {
// whatever logic you want here
return (???)
}
So in this case you could do something like
doctorsApptData.map((apptData, index) => {
if (apptData.date >= DateTime.now()){
return(
<div>This date is valid! {apptData.date}</div>
)
}
)
or if you really wanted to use a ternary (personally I'd be a little wary against using them too sparsely since they tend to compromise code readability):
doctorsApptData.map((apptData, index) => {
return(
apptData.date >= DateTime.now && (<div>This date is valid! {apptData.date}</div>)
)
}
)
hope it helped!
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论