简体   繁体   中英

How to render a string inside jsx <div> using reduce on an array of objects

I want to render a list of flight stops location codes.I have an array of my stops objects:

flight = {
departStops:1,
departSegments:{
 {
    departure: {iataCode: "TXL"},
    arrival: {iataCode: "FRA"}
   },
 {
    departure: {iataCode: "FRA"},
    arrival: {iataCode: "YUL"}
   }
}

inside my component function before the return I created the string constant:

const myString = flight.departSegments.reduce((acc,item) => {
                        if (item.arrival.iataCode !== flight.departSegments[flight.departSegments.length - 1].arrival.iataCode) {
                            if (acc.length > 0) {
                                acc.concat(',',item.arrival.iataCode)
                            } else {
                                acc.concat(item.arrival.iataCode)
                            }
                        }
                        return acc
                    },"")

and this is how I render my string inside the component:

<div>
    {
        flight.departStops > 0 
        ?
        myString
        : 
        null
    }
</div>

the problem is that myString remains an empty string on rendering

Strings are immutable in javascript in order to make it work you need to return acc.concat() result

const flight = {
  departStops: 1,
  departSegments: [
    {
      departure: { iataCode: 'TXL' },
      arrival: { iataCode: 'FRA' }
    },
    {
      departure: { iataCode: 'FRA' },
      arrival: { iataCode: 'YUL' }
    }
  ]
}

const myString = flight.departSegments.reduce((acc, item) => {
  if (
    item.arrival.iataCode !==
    flight.departSegments[flight.departSegments.length - 1].arrival.iataCode
  ) {
    if (acc.length > 0) {
      return acc.concat(',', item.arrival.iataCode)
    } else {
      return acc.concat(item.arrival.iataCode)
    }
  }
  return acc
}, '')

console.log(myString)

PS

You may simplify your render

<div> { (flight.departStops > 0) && myString } </div> 

You need to return from reduce like this

if (item.arrival.iataCode !== flight.departSegments[flight.departSegments.length - 1].arrival.iataCode) {
    if (acc.length > 0) {
         return acc.concat(',',item.arrival.iataCode)
    } else {
         return acc.concat(item.arrival.iataCode)
    }
  }

Also, the way you constructed departSegments is bad. It should be array, and not object.

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