简体   繁体   中英

React Native Conditional Mapping Return

I have an array, splitByDay :

Array [
  Object {
    "Day": "Sunday",
    "data": "Upper",
  },
  Object {
    "Day": "Monday",
    "data": "Lower",
  },
]

and a function:

const getDay = (it) => {

          splitByDay.map((x, i) => {
            let day = x["Day"];
              if (day === it){

              return x["data"]
              } else { return "Rest" }
            
          })
      }

inside a FlatList , I pass in it which is the current day.

My goal is to return the corresponding piece of data if the day aligns. Here is the how its called:

 <Text style={[tailwind(`text-gray-300 font-[400px] text-[11px]`), {color: item === currentDay ? colors.purple : 'white'}]}>{getDay(item)}</Text>

The problem is that you try to filter and map the data at once inside the map function. You should split that up, first filter the data and then map the data you want.

For example this code:

  const getDay = (it) => {
    return splitByDay.filter((x)=> x["Day"] === it).map((x) => x["Data"])[0]
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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