Home > front end >  React Native Conditional Mapping Return
React Native Conditional Mapping Return

Time:07-09

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>

CodePudding user response:

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]
  }
  • Related